三个水杯
时间限制:
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<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<iostream> #include<algorithm> #include<queue> #include<stack> using namespace std; struct cup { int v[4]; int step; }; cup now,next; queue<cup>q; int visit[110][110]; int V[4]; //杯子的编号 int E[4]; //需要的最终状态 int e[4];//杯子盛水状态 int num,flag; int Min; void push() // 将未曾访问过的水杯模式入队 { now.v[1]=e[1]; now.v[2]=e[2]; now.v[3]=e[3]; now.step=num; q.push(now); visit[e[1]][e[2]]=1; } void pour_water(int x,int y) //从x 杯子里往y杯子里倒水 { e[6-x-y]=next.v[6-x-y]; if(V[y]-next.v[y]>=next.v[x])//能否将x杯里的水全部到入y杯中 { e[x]=0; // 现在x杯的水 e[y]=next.v[x]+next.v[y];//现在y杯的水 if(!visit[e[1]][e[2]])//得到的水杯模式没有被搜索过 push(); } else { e[x]=next.v[x]-(V[y]-next.v[y]); e[y]=V[y]; if(!visit[e[1]][e[2]]) push(); } } void BFS() { now.v[1]=V[1]; now.v[2]=now.v[3]=now.step=0; q.push(now); while(!q.empty()) { next=q.front(); q.pop(); e[1]=next.v[1]; e[2]=next.v[2]; e[3]=next.v[3]; num=next.step; if(e[1]==E[1] && e[2]==E[2] &&e[3]==E[3]&& num<Min) //符合条件,达到目标 { Min=num; flag=1; } num=next.step+1; //三只水杯互相倒水,遍历产生不同的杯水匹配,再依次访问,求出最小的 if(next.v[1]>0) { pour_water(1,2); pour_water(1,3); } if(next.v[2]>0) { pour_water(2,1); pour_water(2,3); } if(next.v[3]>0) { pour_water(3,1); pour_water(3,2); } } } int main() { int n; while(~scanf("%d",&n)) { while(n--) { flag=0; Min=999999999; memset(visit,0,sizeof(visit)); scanf("%d%d%d%d%d%d",&V[1],&V[2],&V[3],&E[1],&E[2],&E[3]); //cin>>V[1]>>V[2]>>V[3]>>E[1]>>E[2]>>E[3]; BFS(); if(flag) printf("%d\n",Min); else printf("-1\n"); // if(flag) // cout<<Min<<endl; // else // cout<<-1<<endl; } } return 0; }
-
-
第一行一个整数N(0<N<50)表示N组测试数据