Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
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 3
4 1 3
0 0 0
Sample Output
NO
3
Source
“2006校园文化活动月”之“校庆杯”大学生程序设计竞赛暨杭州电子科技大学第四届大学生程序设计竞赛
思路:倒水问题,白书例题,很经典的BFS。每个状态是当前三个杯子的水容量。
AC代码:
#include <cstdio> #include <queue> #include <cstring> using namespace std; int s, n, m; bool vis[105][105][105]; struct node { int s, n, m; int step; bool ok() { if ((!s && n == m) || (!n && s == m) || (!m && s == n)) return 1; return 0; } }; queue <node> q; void pre() { while (!q.empty()) q.pop(); memset(vis, 0, sizeof(vis)); } void bfs() { pre(); q.push((node){s, 0, 0, 0}); vis[s][0][0] = 1; while (!q.empty()) { node u = q.front(); q.pop(); if (u.ok()) { printf("%d\n", u.step); return; } node next; int change; if (u.s) { if (u.n < n) { next = u; change = min(u.s, n - u.n); next.s -= change; next.n += change; next.step = u.step + 1; if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; q.push(next); } } if (u.m < m) { next = u; change = min(u.s, m - u.m); next.s -= change; next.m += change; next.step = u.step + 1; if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; q.push(next); } } } if (u.n) { next = u; next.n = 0; next.s += u.n; next.step = u.step + 1; if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; q.push(next); } if (u.m < m) { next = u; change = min(u.n, m - u.m); next.n -= change; next.m += change; next.step = u.step + 1; if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; q.push(next); } } } if (u.m) { next = u; next.m = 0; next.s += u.m; next.step = u.step + 1; if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; q.push(next); } if (u.n < n) { next = u; change = min(u.m, n - u.n); next.m -= change; next.n += change; next.step = u.step + 1; if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; q.push(next); } } } } printf("NO\n"); } int main() { while (scanf("%d%d%d", &s, &n, &m) == 3 && s) { if (s % 2) printf("NO\n"); else if (n == m) printf("1\n"); else bfs(); } return 0; }
0 条评论