Pots Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 11551 Accepted: 4900 Special Judge
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 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.
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)
題意:
兩個杯子,一個勺,兩個杯子的水量通過勺子裝水或倒水操作變化,求最初狀態變化到最終狀態所需最小步數。
思路:
bfs遍歷,每次有6種變化,由最初狀態變化到最終狀態所需最小步數。
代碼:
#include#include #define MAX 10001 typedef struct Node { int a,b,step,pre,flag; }; int A,B,C; Node queue[MAX]; bool visit[101][101]; int path[MAX],index; void bfs() { memset(visit,false,sizeof(visit)); int front=0,rear=0; Node cur,next; cur.a=0,cur.b=0,cur.pre=-1,cur.step=0; visit[0][0]=true; queue[rear++]=cur; while(front!=rear) { cur=queue[front++]; if(cur.a==C||cur.b==C) break; for(int i=0;i<6;i++) { switch(i) { case 0: next.a=A; next.b=cur.b; next.flag=0; break; case 1:next.a=cur.a; next.b=B; next.flag=1; break; case 2:next.a=0; next.b=cur.b; next.flag=2; break; case 3:next.a=cur.a; next.b=0; next.flag=3; break; case 4: if(B-cur.b =0;) { path[index++]=i; i=queue[i].pre; } printf(%d ,queue[front-1].step); for(int i=index-1;i>=0;i--) { switch(queue[path[i]].flag) { case 0:printf(FILL(1) );break; case 1:printf(FILL(2) ); break; case 2:printf(DROP(1) ); break; case 3:printf(DROP(2) ); break; case 4:printf(POUR(1,2) ); break; case 5:printf(POUR(2,1) ); break; } } } int main() { scanf(%d %d %d,&A,&B,&C); bfs(); return 0; }