注解
1、遍历6种情况:a往b倒,a往c倒,b往c倒,b往a倒,c往b倒,c往a倒。
2、能倒的条件是,前一个不空,后一个不满。倒的时候分两种情况:(1)前一个的水能全部倒到后一个杯子里;(2)前一个的水只倒一部分到后一个杯子,后一个容量就满了。
3、注意初始状态和结束状态,初始状态第一个杯子为满,第二个第三个杯子为空;结束状态是有两个杯子容量相等,另一个杯子为空。
4、注意visit数组的设置。
代码
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 101;
int S, N, M;
int visit[MAXN][MAXN][MAXN];
struct Node {
int a;
int b;
int c;
int step;
};
int BFS() {
memset(visit, 0, sizeof(visit));
queue<Node> q;
Node node;
node.a = S;
node.b = 0;
node.c = 0;
visit[S][0][0] = 1;
q.push(node);
while(q.size()>0) {
Node top = q.front();
q.pop();
if(top.a==S/2 && top.b==S/2) {
return top.step;
} else if(top.b==S/2 && top.c==S/2) {
return top.step;
} else if(top.a==S/2 && top.c==S/2) {
return top.step;
} else {
Node next;
next.step = top.step+1;
//a->b
if(top.a && top.b!=N) {
if(top.a >= N-top.b) {
next.a = top.a - (N-top.b);
next.b = N;
next.c = top.c;
} else {
next.a = 0;
next.b = top.b+top.a;
next.c = top.c;
}
if(!visit[next.a][next.b][next.c]) {
q.push(next);
visit[next.a][next.b][next.c] = 1;
}
}
//a->c
if(top.a && top.c!=M) {
if(top.a >= M-top.c) {
next.a = top.a - (M-top.c);
next.b = top.b;
next.c = M;
} else {
next.a = 0;
next.b = top.b;
next.c = top.c+top.a;
}
if(!visit[next.a][next.b][next.c]) {
q.push(next);
visit[next.a][next.b][next.c] = 1;
}
}
//b->a
if(top.b && top.a!=S) {
if(top.b >= S-top.a) {
next.a = S;
next.b = top.b-(S-top.a);
next.c = top.c;
} else {
next.a = top.a+top.b;
next.b = 0;
next.c = top.c;
}
if(!visit[next.a][next.b][next.c]) {
q.push(next);
visit[next.a][next.b][next.c] = 1;
}
}
//b->c
if(top.b && top.c!=M) {
if(top.b >= M-top.c) {
next.a = top.a;
next.b = top.b-(M-top.c);
next.c = M;
} else {
next.a = top.a;
next.b = 0;
next.c = top.c+top.b;
}
if(!visit[next.a][next.b][next.c]) {
q.push(next);
visit[next.a][next.b][next.c] = 1;
}
}
//c->a
if(top.c && top.a!=S) {
if(top.c >= S-top.a) {
next.a = S;
next.b = top.b;
next.c = top.c-(S-top.a);
} else {
next.a = top.a+top.c;
next.b = top.b;
next.c = 0;
}
if(!visit[next.a][next.b][next.c]) {
q.push(next);
visit[next.a][next.b][next.c] = 1;
}
}
//c->b
if(top.c && top.b!=N) {
if(top.c >= N-top.b) {
next.a = top.a;
next.b = N;
next.c = top.c - (N-top.b);
} else {
next.a = top.a;
next.b = top.b+top.c;
next.c = 0;
}
if(!visit[next.a][next.b][next.c]) {
q.push(next);
visit[next.a][next.b][next.c] = 1;
}
}
}
}
return 0;
}
int main() {
scanf("%d %d %d", &S, &N, &M);
while(S || N || M) {
if(S%2) {
printf("NO\n");
} else {
if(N<M) {
swap(N, M);
}
int ans = BFS();
if(ans){
printf("%d\n", ans);
}
else{
printf("NO\n");
}
}
scanf("%d %d %d", &S, &N, &M);
}
return 0;
}