标签:
Description:
Input:
Output:
Sample Input:
Sample Output:
#include<stdio.h> #include<queue> #include<string.h> #include<algorithm> using namespace std; const int maxn=110; struct node { int s, n, m, k; ///s,n,m分别表示可乐瓶和两个杯子中可乐的容量,k表示倒可乐的次数 }; int S, N, M, vis[maxn][maxn][maxn]; int BFS() { node now, next; queue<node>Q; now.s = S; now.n = now.m = now.k = 0; Q.push(now); vis[now.s][now.n][now.m] = 1; while (!Q.empty()) { now = Q.front(); Q.pop(); if ((now.s==S/2 && now.n==S/2) || (now.s==S/2 && now.m==S/2) || (now.n==S/2 && now.m==S/2)) return now.k; ///题中要求只要能平分就行,所以不管哪两个杯子装的是平分的可乐都行 ///接下来就是三个杯子分别有可乐的情况,每种情况中又分别判断了另两个杯子的状态,所以一共是六种 if (now.s != 0) { if (now.s <= N-now.n) { next.s = 0; next.n = now.n+now.s; next.m = now.m; next.k = now.k+1; } else { next.s = now.s-(N-now.n); next.n = N; next.m = now.m; next.k = now.k+1; } if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; Q.push(next); } if (now.s <= M-now.m) { next.s = 0; next.n = now.n; next.m = now.m+now.s; next.k = now.k+1; } else { next.s = now.s-(M-now.m); next.n = now.n; next.m = M; next.k = now.k+1; } if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; Q.push(next); } } if (now.n != 0) { if (now.n <= S-now.s) { next.s = now.s+now.n; next.n = 0; next.m = now.m; next.k = now.k+1; } else { next.s = S; next.n = now.n-(S-now.s); next.m = now.m; next.k = now.k+1; } if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; Q.push(next); } if (now.n <= M-now.m) { next.s = now.s; next.n = 0; next.m = now.m+now.n; next.k = now.k+1; } else { next.s = now.s; next.n = now.n-(M-now.m); next.m = M; next.k = now.k+1; } if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; Q.push(next); } } if (now.m != 0) { if (now.m <= S-now.s) { next.s = now.s+now.m; next.n = now.n; next.m = 0; next.k = now.k+1; } else { next.s = S; next.n = now.n; next.m = now.m-(S-now.s);; next.k = now.k+1; } if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; Q.push(next); } if (now.m <= N-now.n) { next.s = now.s; next.n = now.m+now.n; next.m = 0; next.k = now.k+1; } else { next.s = now.s; next.n = N; next.m = now.m-(N-now.n); next.k = now.k+1; } if (!vis[next.s][next.n][next.m]) { vis[next.s][next.n][next.m] = 1; Q.push(next); } } } return -1; } int main () { int ans; while (scanf("%d%d%d", &S, &N, &M), S+N+M) { memset(vis, 0, sizeof(vis)); if (S % 2 != 0) printf("NO\n"); ///当然可乐的容量原本就是奇数,是肯定不会被平分的 else { ans = BFS(); if (ans == -1) printf("NO\n"); else printf("%d\n", ans); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/syhandll/p/4828503.html