三个水杯
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
给出三个水杯,大小不一,并且只有最大的水杯的水是装满的,其余两个为空杯子。三个水杯之间相互倒水,并且水杯没有标识,只能根据给出的水杯体积来计算。现在要求你写出一个程序,使其输出使初始状态到达目标状态的最少次数。
-
输入
-
第一行一个整数N(0<N<50)表示N组测试数据
接下来每组测试数据有两行,第一行给出三个整数V1 V2 V3 (V1>V2>V3 V1<100 V3>0)表示三个水杯的体积。
第二行给出三个整数E1 E2 E3 (体积小于等于相应水杯体积)表示我们需要的最终状态
输出
- 每行输出相应测试数据最少的倒水次数。如果达不到目标状态输出-1 样例输入
-
2 6 3 1 4 1 1 9 3 2 7 1 1
样例输出
-
3
-1
-
对于每一次倒水都会引起三个水杯水量状态的改变,这样就可以得到如下的一个解空间树:
#include<stdio.h> #include<string.h> #include<queue> using namespace std; int cupCapacity[3]; int finalState[3]; int visited[101][101][101]; struct node{ int waterState[3]; int steps; }start; void pourWater(int destination,int source,node &cup)//I missed the & annotation at the beginning n that costs me a lot of time ,remember to add & whenever it comes to the data change of some exact variebles~~ { int waterRemain = cupCapacity[destination] - cup.waterState[destination]; if(cup.waterState[source] >= waterRemain) { cup.waterState[destination] = cupCapacity[destination]; cup.waterState[source] -= waterRemain; } else { cup.waterState[destination] += cup.waterState[source]; cup.waterState[source] = 0; } } bool reachFianlState(node s) { int i; for(i = 0;i < 3;i++) { if(finalState[i] != s.waterState[i]) return false; } return true; } int bfs() { int i,j,k; queue<node> q; q.push(start); visited[start.waterState[0]][0][0] = 1; while(!q.empty()) { node cur = q.front(); q.pop(); if(reachFianlState(cur)) { return cur.steps; } else for(i = 0;i < 3;i++) { for(j = 1;j < 3;j++) { k = (i + j)%3; if(cur.waterState[i] != 0 && cur.waterState[k] < cupCapacity[k]) { node temp = cur; pourWater(k,i,temp); temp.steps = cur.steps + 1; if(!visited[temp.waterState[0]][temp.waterState[1]][temp.waterState[2]]) { visited[temp.waterState[0]][temp.waterState[1]][temp.waterState[2]] = 1; q.push(temp); } } } } } return -1; } int main() { int cases; int ans; scanf("%d",&cases); while(cases--) { scanf("%d%d%d",&cupCapacity[0],&cupCapacity[1],&cupCapacity[2]); scanf("%d%d%d",&finalState[0],&finalState[1],&finalState[2]); memset(visited,0,sizeof(visited)); start.waterState[0] = cupCapacity[0]; start.waterState[1] = 0; start.waterState[2] = 0; start.steps = 0; ans = bfs(); printf("%d\n",ans); } return 0; }
-
第一行一个整数N(0<N<50)表示N组测试数据