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:
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 <stdio.h> #include <memory.h> #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<cur.a) { next.a=cur.a+cur.b-B; next.b=B; next.flag=4; } else { next.a=0; next.b=cur.a+cur.b; next.flag=4; } break; default: if(A-cur.a<cur.b) { next.a=A; next.b=cur.a+cur.b-A; next.flag=5; } else { next.a=cur.a+cur.b; next.b=0; next.flag=5; } }//遍历完由该状态可以到达的状态 if(!visit[next.a][next.b]) { next.step=cur.step+1; next.pre=front-1;//[front++] queue[rear++]=next; visit[next.a][next.b]=true; } } } if(front==rear) {printf("impossible/n"); return ;} index=0; for(int i=front-1;i>=0;) { path[index++]=i; i=queue[i].pre; } printf("%d\n",queue[front-1].step); for(int i=index-1;i>=0;i--) { switch(queue[path[i]].flag) { case 0:printf("FILL(1)\n");break; case 1:printf("FILL(2)\n"); break; case 2:printf("DROP(1)\n"); break; case 3:printf("DROP(2)\n"); break; case 4:printf("POUR(1,2)\n"); break; case 5:printf("POUR(2,1)\n"); break; } } } int main() { scanf("%d %d %d",&A,&B,&C); bfs(); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/kaisa158/article/details/46917399