「POJ3414」Pots
题目描述
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 i to 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.
输入
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).
输出
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’.
样例输入
样例输出
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
#include<iostream> using namespace std; int p1,p2,e,m; int t=0,w=1,ans=0; int d[10000][3],step[10000],father[10000],mv[10000],a[10000]; bool pd(int x,int y) { for(int k=0;k<=w;k++) if(d[k][1]==x&&d[k][2]==y)return 0; else continue; return 1; } void an() { if(d[w][1]==e||d[w][2]==e) { ans=1; cout<<step[w]<<endl; int s=w; while(1){ a[step[s]]=mv[s]; s=father[s]; if(s==0)break; } for(int i=1;i<=step[w];i++) { if(a[i]==1)cout<<"FILL(1)"; if(a[i]==2)cout<<"FILL(2)"; if(a[i]==3)cout<<"DROP(1)"; if(a[i]==4)cout<<"DROP(2)"; if(a[i]==5)cout<<"POUR(1,2)"; if(a[i]==6)cout<<"POUR(2,1)"; cout<<endl; } } } void search() { while(t<w) { if(ans==1)return; if(pd(p1,d[t][2])){w++;step[w]=step[t]+1;mv[w]=1;father[w]=t; d[w][1]=p1;d[w][2]=d[t][2];an();} if(pd(d[t][1],p2)){w++;step[w]=step[t]+1;mv[w]=2;father[w]=t; d[w][1]=d[t][1];d[w][2]=p2;an();} if(pd(0,d[t][2])){w++;step[w]=step[t]+1;mv[w]=3;father[w]=t; d[w][1]=0;d[w][2]=d[t][2];an();} if(pd(d[t][1],0)){w++;step[w]=step[t]+1;mv[w]=4;father[w]=t; d[w][1]=d[t][1];d[w][2]=0;an();} m=min(d[t][1],p2-d[t][2]); if(pd(d[t][1]-m,d[t][2]+m)){w++;step[w]=step[t]+1;mv[w]=5;father[w]=t; d[w][1]=d[t][1]-m;d[w][2]=d[t][2]+m;an();} m=min(p1-d[t][1],d[t][2]); if(pd(d[t][1]+m,d[t][2]-m)){w++;step[w]=step[t]+1;mv[w]=6;father[w]=t; d[w][1]=d[t][1]+m;d[w][2]=d[t][2]-m;an();} t++; } } int main() { cin>>p1>>p2>>e; search(); if(ans==0)cout<<"impossible"; return 0; } |