Pots
Pots
Description
You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
- FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
- DROP(i) empty the pot ito the drain;
- POUR(i,j) pour from pot i to pot j; after this operation either the pot j is full (and there may be some water left in the pot i), or the pot i is empty (and all its contents have been moved to the pot j).
Write a program to find the shortest possible sequence of these operations that will yield exactly C liters of water in one of the pots.
Input
On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 and C≤max(A,B).
Output
The first line of the output must contain the length of the sequence of operations K. The following K lines must each describe one operation. If there are several sequences of minimal length, output any one of them. If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.
Sample Input
3 5 4
Sample Output
6 FILL(2) POUR(2,1) DROP(1) POUR(2,1) FILL(2) POUR(2,1)
/*分析题意: 给出两个容积分别为vol1 和vol2的pot,按照六种操作,求出能否在一定步数后,使其中一个pot的水量为drain。 1.FILL(1):将pot1倒满水 2.FILL(2):将pot2倒满水 3.DROP(1):将pot1水倒空 4.DROP(2):将pot2水倒空 5.POUR(1,2): 将pot1的水倒到pot2中,可有剩余 6.POUR(2,1): 将pot2的水倒到pot1中,可有剩余 思路: BFS求最短路径步数,并在过程中记录路径,用并查集查找*/ # include<iostream> # include<cstring> # include<queue> using namespace std; int drain,cnt; int vis[105][105]; char sign[10010][20],k; int parent[10010],t[10010],Id; struct node { int num1,num2; int vol1,vol2; int step; char opera[20]; int seq; }p; void find(int s)//查找到根节点 { if(s!=parent[s]) { t[Id++]=s; find(parent[s]); } } struct node Judge(int n,node s)//六个操作 { if(n==0) { strcpy(s.opera,"FILL(1)"); s.num1=s.vol1; } else if(n==1) { strcpy(s.opera,"FILL(2)"); s.num2=s.vol2; } else if(n==2) { strcpy(s.opera,"DROP(1)"); s.num1=0; } else if(n==3) { strcpy(s.opera,"DROP(2)"); s.num2=0; } else if(n==4) { strcpy(s.opera,"POUR(1,2)"); if(s.num1<(s.vol2-s.num2))//判断能否倒完 { s.num2+=s.num1; s.num1=0; } else { s.num1-=(s.vol2-s.num2); s.num2=s.vol2; } } else { strcpy(s.opera,"POUR(2,1)"); if(s.num2<s.vol1-s.num1) { s.num1+=s.num2; s.num2=0; } else { s.num2-=(s.vol1-s.num1); s.num1=s.vol1; } } return s; } void bfs() { int i; queue<node>C; p.num1=0; p.num2=0; p.step=0; p.seq=0; cnt=0; parent[cnt]=0; C.push(p); vis[0][0]=1; while(!C.empty())//BFS思想 { node a=C.front(); C.pop(); for(i=0;i<6;i++) { node b=a; b=Judge(i,b); b.step++; if(b.num1==drain||b.num2==drain) { parent[++cnt]=a.seq; b.seq=cnt; strcpy(sign[cnt],b.opera); cout<<b.step<<endl; find(cnt); for(i=Id-1;i>=0;i--) { cout<<sign[t[i]]<<endl; } return; } else if(!vis[b.num1][b.num2]) { vis[b.num1][b.num2]=1; cnt++; b.seq=cnt;//记录自身节点位置 strcpy(sign[cnt],b.opera);//记录操作 parent[cnt]=a.seq;//标记父节点 C.push(b); } } } cout<<"impossible"<<endl; } int main() { cin>>p.vol1>>p.vol2>>drain; memset(vis,0,sizeof(vis)); Id=0; bfs(); return 0; }
浙公网安备 33010602011771号