描述
给出三个水杯,大小不一,并且只有最大的水杯的水是装满的,其余两个为空杯子。三个水杯之间相互倒水,并且水杯没有标识,只能根据给出的水杯体积来计算。现在要求你写出一个程序,使其输出使初始状态到达目标状态的最少次数。
-
输入
-
第一行一个整数N(0<N<50)表示N组测试数据
接下来每组测试数据有两行,第一行给出三个整数V1 V2 V3 (V1>V2>V3 V1<100 V3>0)表示三个水杯的体积。
第二行给出三个整数E1 E2 E3 (体积小于等于相应水杯体积)表示我们需要的最终状态
输出
-
2 6 3 1 4 1 1 9 3 2 7 1 1
样例输出
-
3 -1
BFS即可:
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <vector> #include <math.h> #include <queue> #include <algorithm> #include <time.h> #define MAXX 1500 using namespace std; struct state{ int a, b, c; int step; //最小步数 state(){ a = b = c = step = 0;} }b,e; int v1, v2, v3, e1, e2, e3; int visit[105][105][105]; //状态是否出现过 int bfs(state begin){ queue<state> q; while(!q.empty()) q.pop(); q.push(begin); while(!q.empty()){ state cur = q.front(); q.pop(); visit[cur.a][cur.b][cur.c] = 1; //printf("a: %d b: %d c: %d\n", cur.a, cur.b, cur.c); if(cur.a == e.a && cur.b == e.b && cur.c == e.c) return cur.step; //find it if(cur.a > 0 && cur.b < v2) //v1->v2 { state temp = cur; int tv = min(cur.a, v2-cur.b); //能倒的水 temp.a -= tv; temp.b += tv; if(!visit[temp.a][temp.b][temp.c]) //如果状态没出现过 { visit[temp.a][temp.b][temp.c] = 1; temp.step++; q.push(temp); } } if(cur.a > 0 && cur.c < v3) //v1->v3 { state temp = cur; int tv = min(cur.a, v3-cur.c); //能倒的水 temp.a -= tv; temp.c += tv; if(!visit[temp.a][temp.b][temp.c]) //如果状态没出现过 { visit[temp.a][temp.b][temp.c] = 1; temp.step++; q.push(temp); } } if(cur.b > 0 && cur.c < v3) //v2->v3 { state temp = cur; int tv = min(cur.b, v3-cur.c); //能倒的水 temp.b -= tv; temp.c += tv; if(!visit[temp.a][temp.b][temp.c]) //如果状态没出现过 { visit[temp.a][temp.b][temp.c] = 1; temp.step++; q.push(temp); } } if(cur.b > 0 && cur.a < v1) //v2->v1 { state temp = cur; int tv = min(cur.b, v1-cur.a); //能倒的水 temp.b -= tv; temp.a += tv; if(!visit[temp.a][temp.b][temp.c]) //如果状态没出现过 { visit[temp.a][temp.b][temp.c] = 1; temp.step++; q.push(temp); } } if(cur.c > 0 && cur.a < v1) //v3->v1 { state temp = cur; int tv = min(cur.c, v1-cur.a); //能倒的水 temp.c -= tv; temp.a += tv; if(!visit[temp.a][temp.b][temp.c]) //如果状态没出现过 { visit[temp.a][temp.b][temp.c] = 1; temp.step++; q.push(temp); } } if(cur.c > 0 && cur.b < v2) //v3->v2 { state temp = cur; int tv = min(cur.c, v2-cur.b); //能倒的水 temp.c -= tv; temp.b += tv; if(!visit[temp.a][temp.b][temp.c]) //如果状态没出现过 { visit[temp.a][temp.b][temp.c] = 1; temp.step++; q.push(temp); } } } return -1; } int main(int argc, char *argv[]) { //freopen("test.in", "r", stdin); int ncase; cin >> ncase; while(ncase--) { memset(visit, 0, sizeof(visit)); b.a = 0; b.b = 0; b.c = 0; b.step = 0; e.a = 0; e.b = 0; e.c = 0; e.step = 0; scanf("%d%d%d", &v1, &v2, &v3); scanf("%d%d%d", &e1, &e2, &e3); b.a = v1; e.a = e1; e.b = e2; e.c = e3; if(v1 < e1+e2+e3) printf("-1\n"); else printf("%d\n", bfs(b)); } return 0; }
每行输出相应测试数据最少的倒水次数。如果达不到目标状态输出-1
样例输入