【BFS】HDU 1495
题意:中文题,不解释。
思路:三个杯子倒来倒去,最后能让其中两个平分即可。可能性六种。判定的时候注意第三个杯子不能有水,倒的时候也要注意别超过了倒进去的杯子的容积。
a->b || a->c || b->a || b->c || c->a || c->b
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int vis[105][105][105];
struct node{
int s,n,m;
int step;
};
bool check(int S,int N,int M){
if(S==0&&(N==M))
return true;
if(N==0&&(S==M))
return true;
if(M==0&&(S==N))
return true;
return false;
}
int bfs(int S,int M,int N){
queue<node>Q;
node P,T;
P.s = S;
P.m = 0;
P.n = 0;
P.step = 0;
vis[S][0][0] = 1;
Q.push(P);
while(Q.size()){
P = Q.front();
Q.pop();
if(check(P.s,P.m,P.n)){
return P.step;
}
if(P.s){
if(P.s>N-P.n){
T.s = P.s-(N-P.n);
T.n = N;
T.m = P.m;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
else{
T.s = 0;
T.n = P.s+P.n;
T.m = P.m;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
if(P.s>M-P.m){
T.s = P.s-(M-P.m);
T.m = M;
T.n = P.n;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
else{
T.s = 0;
T.m = P.s+P.m;
T.n = P.n;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
}
if(P.m){
if(P.m>N-P.n){
T.m = P.m-(N-P.n);
T.n = N;
T.s = P.s;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
else{
T.m = 0;
T.n = P.n+P.m;
T.s = P.s;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
if(P.m>S-P.s){
T.m = P.m-(S-P.s);
T.s = S;
T.n = P.n;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
else{
T.m = 0;
T.s = P.s+P.m;
T.n = P.n;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
}
if(P.n){
if(P.n>S-P.s){
T.n = P.n-(S-P.s);
T.s = S;
T.m = P.m;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
else{
T.n = 0;
T.s = P.s+P.n;
T.m = P.m;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
if(P.n>M-P.m){
T.n = P.n-(M-P.m);
T.m = M;
T.s = P.s;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
else{
T.n = 0;
T.m = P.m+P.n;
T.s = P.s;
if(!vis[T.s][T.n][T.m]){
T.step=P.step+1;
Q.push(T);
vis[T.s][T.n][T.m] = 1;
}
}
}
}
return -1;
}
int main(){
int S,M,N;
while(~scanf("%d%d%d",&S,&N,&M)){
if(S==0&&N==0&&M==0){
break;
}
if(S%2){
printf("NO\n");
continue;
}
memset(vis,0,sizeof(vis));
int ans = bfs(S,M,N);
if(ans==-1) printf("NO\n");
else printf("%d\n",ans);
}
return 0;
}