具体有图参考:http://blog.youkuaiyun.com/code_pang/article/details/7802944
#include <stdio.h>
#include <string.h>
#include<iostream>
#include <queue>
using namespace std;
int visit[100][100][100];
typedef struct state {
int state[3];
int step;
} State;
int target[3], begin[3];
//与目标对比,符合目标返回1,否则返回0
int reachTarget(State cup) {
for(int i=0; i<3; i++) {
if(cup.state[i] != target[i])
return 0;
}
return 1;
}
//curr 向dest倒水
void pourWater(int dest, int curr, State &cup) {
int water = begin[dest] - cup.state[dest]; //dest杯子剩余容量
if(cup.state[curr] >= water) {
cup.state[curr] -= water;
cup.state[dest] += water;
}
else {
cup.state[dest] += cup.state[curr];
cup.state[curr] = 0;
}
}
//广搜水杯状态
int bfs() {
State now;
memset(visit, 0, sizeof(visit));
now.state[0] = begin[0];
now.state[1] = now.state[2] = 0;
now.step = 0;
queue <State> waterstate;
waterstate.push(now);
//标记
visit[now.state[0]][now.state[1]][now.state[2]] = 1;
while(!waterstate.empty()) {
State temp = waterstate.front();
waterstate.pop();
if(reachTarget(temp))
return temp.step;
//简化为一个杯子想另一个杯子倒水
for(int i=0; i<3; i++) {
for(int j=0; j<3; j {
int k = (i+j)%3;
if(temp.state[i] !=0 && temp.state[k] < begin[k]) {
State newT = temp;
pourWater(k, i, newT);
newT.step = temp.step + 1;
if(!visit[newT.state[0]][newT.state[1]][newT.state[2]]) {
visit[newT.state[0]][newT.state[1]][newT.state[2]] = 1;
waterstate.push(newT);
}
}
}
}
}
return -1;
}
int main(void) {
int t;
scanf("%d", &t);
while(t--) {
scanf("%d%d%d", &begin[0], &begin[1], &begin[2]);
scanf("%d%d%d", &target[0], &target[1], &target[2]);
printf("%d\n", bfs());
}
return 0;
}
oj给的最优代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<bitset>
using namespace std;
#define CLR(arr,val) memset(arr,val,sizeof(arr))
bitset<1000000> Hash;
const int MAX_STEP=100000;
int WQ[MAX_STEP][4],Goal[3],Cap[3],goalval;
int head=0,tail=0;
void movw(int numfrom,int numto,int other)
{
int total=WQ[head][numfrom]+WQ[head][numto];
WQ[tail][other]=WQ[head][other];
WQ[tail][3]=WQ[head][3]+1;
if(total>Cap[numto])
{
WQ[tail][numfrom]=total-Cap[numto];
WQ[tail][numto]=Cap[numto];
}
else
{
WQ[tail][numfrom]=0;
WQ[tail][numto]=total;
}
int hashval=WQ[tail][0]*10000+WQ[tail][1]*100+WQ[tail][2];
if(hashval==goalval) throw WQ[head][3]+1;
if(WQ[head][numfrom]!=0 && !Hash[hashval])
{
Hash[hashval]=true;
if(++tail==MAX_STEP) tail=0;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
Hash.reset();
scanf("%d%d%d%d%d%d",&Cap[0],&Cap[1],&Cap[2],&Goal[0],&Goal[1],&Goal[2]);
head=0,tail=0,goalval=Goal[0]*10000+Goal[1]*100+Goal[2];
if(Goal[1]==0 && Goal[2]==0 && Goal[0]==Cap[0]) {puts("0");continue;}
WQ[tail][0]=Cap[0];WQ[tail][1]=0;WQ[tail][2]=0;WQ[tail][3]=0;
++tail;
try{
while(head!=tail)
{
movw(0,1,2);movw(1,2,0);movw(0,2,1);movw(1,0,2);movw(2,1,0);movw(2,0,1);
if(++head==MAX_STEP) head=0;
}
puts("-1");
}catch(int step)
{
printf("%d\n",step);
}
}
}