题意很明确
#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
struct node {
int cup[4];
int step;
};
int vis[105][105][105];//标记数组
int b[3];//代表瓶子的容量
int bfs(node s, node e) {
queue<node> q;
node t;//临时变量
memset(vis, 0, sizeof(vis));
vis[s.cup[0]][s.cup[1]][s.cup[2]] = 1;
q.push(s);
while(!q.empty()) {
t = q.front();
q.pop();
if(t.cup[0] == e.cup[0] && t.cup[1] == e.cup[1] && t.cup[2] == e.cup[2]) {
printf("%d\n", t.step);
return 1;
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(i == j || t.cup[i] == 0) continue;//水杯相同不能倒水, i杯没有水可以倒
//从i向j里倒水, 倒水的量是 j杯子容量减去j杯子当前杯子里的水,或者i水杯中的水,取最小值
int m = min(b[j]- t.cup[j], t.cup[i]);
s = t;
s.cup[i] = t.cup[i] - m;
s.cup[j] = t.cup[j] + m;
s.step = t.step + 1;
if(vis[s.cup[0]][s.cup[1]][s.cup[2]] == 0) {//该状态没出现过
vis[s.cup[0]][s.cup[1]][s.cup[2]] = 1;
q.push(s);
}
}
}
}
return 0;
}
int main() {
int n;
scanf("%d", &n);
while(n--) {
node s, e;
scanf("%d%d%d%d%d%d", &b[0], &b[1], &b[2], &e.cup[0], &e.cup[1], &e.cup[2]);
s.cup[0] = b[0]; s.cup[1] = s.cup[2] = 0;
s.step = 0;
if(bfs(s, e) == 0) printf("-1\n");
}
}
图片引用自:http://blog.csdn.net/code_pang/article/details/7802944