三個水杯
時間限制: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 <iostream>
#include <queue>
#define Max_w 205
using namespace std;
int v1_e, v1_h;
int v2_e, v2_h;
int v3_e, v3_h;
int visited[Max_w][Max_w][Max_w] = {0};
typedef struct cup{
int v1;
int v2;
int v3;
int step;
}Cup;
void bfs(Cup c);
int main (){
int N;
int i, j, d;
Cup c;
scanf("%d", &N);
while(N--){
memset(visited, 0, sizeof(visited));
scanf("%d %d %d", &v1_h, &v2_h, &v3_h);
scanf("%d %d %d", &v1_e, &v2_e, &v3_e);
if(v1_h == v1_e && 0 == v2_e && 0 == v3_e){
printf("0\n");
continue;
}
visited[v1_h][0][0] = 1;
c.v1 = v1_h; c.v2 = 0; c.v3 = 0;
c.step = 0;
bfs(c);
}
return 0;
}
void bfs(Cup c){
int i;
queue<Cup> Q;
Cup temp, temp1;
Q.push(c);
while (!Q.empty()){
temp1 = Q.front();
Q.pop();
if(temp1.v1 == v1_e && temp1.v2 == v2_e && temp1.v3 == v3_e){
printf("%d\n", temp1.step);
return ;
}
for(i = 0; i < 6; i++){
temp = temp1;
if(i == 0 && temp.v1 != 0 && temp.v2 != v2_h){
if(temp.v1 >= v2_h - temp.v2){
temp.v1 -= (v2_h - temp.v2);
temp.v2 = v2_h;
}
else{
temp.v2 += temp.v1;
temp.v1 = 0;
}
temp.step ++;
if(!visited[temp.v1][temp.v2][temp.v3]){
visited[temp.v1][temp.v2][temp.v3] = 1;
Q.push(temp);
}
}
if(i == 1 && temp.v1 != 0 && temp.v3 != v3_h){
if(temp.v1 >= v3_h - temp.v3){
temp.v1 -= (v3_h - temp.v3);
temp.v3 = v3_h;
}
else{
temp.v3 += temp.v1;
temp.v1 = 0;
}
temp.step ++;
if(!visited[temp.v1][temp.v2][temp.v3]){
visited[temp.v1][temp.v2][temp.v3] = 1;
Q.push(temp);
}
}
if(i == 2 && temp.v2 != 0 && temp.v3 != v3_h){
if(temp.v2 >= v3_h - temp.v3){
temp.v2 -= (v3_h - temp.v3);
temp.v3 = v3_h;
}
else{
temp.v3 += temp.v2;
temp.v2 = 0;
}
temp.step ++;
if(!visited[temp.v1][temp.v2][temp.v3]){
visited[temp.v1][temp.v2][temp.v3] = 1;
Q.push(temp);
}
}
if(i == 3 && temp.v2 != 0 && temp.v1 != v1_h){
if(temp.v2 >= v1_h - temp.v1){
temp.v2 -= (v1_h - temp.v1);
temp.v1 = v1_h;
}
else{
temp.v1 += temp.v2;
temp.v2 = 0;
}
temp.step ++;
if(!visited[temp.v1][temp.v2][temp.v3]){
visited[temp.v1][temp.v2][temp.v3] = 1;
Q.push(temp);
}
}
if(i == 4 && temp.v3 != 0 && temp.v2 != v2_h){
if(temp.v3 >= v2_h - temp.v2){
temp.v3 -= (v2_h - temp.v2);
temp.v2 = v2_h;
}
else{
temp.v2 += temp.v3;
temp.v3 = 0;
}
temp.step ++;
if(!visited[temp.v1][temp.v2][temp.v3]){
visited[temp.v1][temp.v2][temp.v3] = 1;
Q.push(temp);
}
}
if(i == 5 && temp.v3 != 0 && temp.v1 != v1_h){
if(temp.v3 >= v1_h - temp.v1){
temp.v3 -= (v1_h - temp.v1);
temp.v1 = v1_h;
}
else{
temp.v1 += temp.v3;
temp.v3 = 0;
}
temp.step ++;
if(!visited[temp.v1][temp.v2][temp.v3]){
visited[temp.v1][temp.v2][temp.v3] = 1;
Q.push(temp);
}
}
}
}
printf("%d\n", -1);
}