1、链接
2、题目
Description
大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。Input
三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。Output
如果能平分的话请输出最少要倒的次数,否则输出"NO"。Sample Input
7 4 34 1 30 0 0Sample Output
NO3
3、解题分析:
求平分可乐的最少次数,彼此互相倒,所以存在6种状态:
①s->n ②s->m
③n->s ④m->s
⑤n->m ⑥m->n
属于bfs搜索类型的题(有状态,求最少)
想明白一个写出来,其余状态都一个思路
4、代码
#includeusing namespace std;struct Volum{ int Vs; int Vn; int Vm; int step;};int vis[105][105];int s,n,m;queue q;int bfs(int a,int b, int c){ while(!q.empty()) { q.pop(); } Volum V1; V1.Vs = s; V1.Vn = 0; V1.Vm = 0; q.push(V1); vis[n][m] = 1; while(!q.empty()) { Volum tmp = q.front(); Volum tmp1; if(tmp.Vn == s/2 && tmp.Vs == s/2) ///tmp 这个结构体中的 Vs 和 Vn 均为 s的一半,符合条件直接返回 { return tmp.step; } ///s -> n 由 s 向 n 倒 if(tmp.Vs && tmp.Vn != n) { int c = n - tmp.Vn; if(tmp.Vs >= c) { tmp1.Vs = tmp.Vs - c; tmp1.Vn = n; } else { tmp1.Vs = 0; tmp1.Vn = tmp.Vn + tmp.Vs; } tmp1.Vm = tmp.Vm; tmp1.step = tmp.step + 1; if(!vis[tmp1.Vn][tmp1.Vm]) { q.push(tmp1); vis[tmp1.Vn][tmp1.Vm] = 1; } } ///s -> m if(tmp.Vs && tmp.Vm != m) { int c = m - tmp.Vm; if(tmp.Vs >= c) { tmp1.Vs = tmp.Vs - c; tmp1.Vm = m; } else { tmp1.Vs = 0; tmp1.Vm = tmp.Vm + tmp.Vs; } tmp1.Vn = tmp.Vn; tmp1.step = tmp.step + 1; if(!vis[tmp1.Vn][tmp1.Vm]) { q.push(tmp1); vis[tmp1.Vn][tmp1.Vm] = 1; } } /// n -> s if(tmp.Vn && tmp.Vs != s) { int c = s - tmp.Vs; if(tmp.Vn >= c) { tmp1.Vn = tmp.Vn - c; tmp1.Vs = s; } else { tmp1.Vn = 0; tmp1.Vs = tmp.Vs + tmp.Vn; } tmp1.Vm = tmp.Vm; tmp1.step = tmp.step + 1; if(!vis[tmp1.Vn][tmp1.Vm]) { q.push(tmp1); vis[tmp1.Vn][tmp1.Vm] = 1; } } /// m -> s if(tmp.Vm && tmp.Vs != s) { int c = s - tmp.Vs; if(tmp.Vm >= c) { tmp1.Vm = tmp.Vm - c; tmp1.Vs = s; } else { tmp1.Vm = 0; tmp1.Vs = tmp.Vs + tmp.Vm; } tmp1.Vn = tmp.Vn; tmp1.step = tmp.step + 1; if(!vis[tmp1.Vn][tmp1.Vm]) { q.push(tmp1); vis[tmp1.Vn][tmp1.Vm] = 1; } } /// n -> m if(tmp.Vn && tmp.Vm != m) { int c = m - tmp.Vm; if(tmp.Vn >= c) { tmp1.Vn = tmp.Vn - c; tmp1.Vm = m; } else { tmp1.Vn = 0; tmp1.Vm = tmp.Vm + tmp.Vn; } tmp1.Vs = tmp.Vs; tmp1.step = tmp.step + 1; if(!vis[tmp1.Vn][tmp1.Vm]) { q.push(tmp1); vis[tmp1.Vn][tmp1.Vm] = 1; } } /// m -> n if(tmp.Vm && tmp.Vn != n) { int c = n - tmp.Vn; if(tmp.Vm >= c) { tmp1.Vm = tmp.Vm - c; tmp1.Vn = n; } else { tmp1.Vm = 0; tmp1.Vn = tmp.Vn + tmp.Vm; } tmp1.Vs = tmp.Vs; tmp1.step = tmp.step + 1; if(!vis[tmp1.Vn][tmp1.Vm]) { q.push(tmp1); vis[tmp1.Vn][tmp1.Vm] = 1; } } q.pop(); } return 0;}int main(){ while(~scanf("%d%d%d",&s,&n,&m)) { memset(vis,0,sizeof(vis)); if(s == 0 && n == 0 && m == 0) break; if(s % 2 != 0){ printf("NO\n"); continue; } if(n