Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 12022 | Accepted: 5078 | 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)
题目大意:有两个杯子的容量分别是A,B,问经过多少步,可以让C升的水装到一个杯子中。
思路:问最短的步数当然是BFS,但是怎么将其路径标记下来是难点,并且怎么个搜索法。
可以设一个串在node 来专门装当前的情况,然后分别映射到str中,对于怎么搜索肯定分为fill,drop,pour三大类
#include<iostream> #include<cstdio> #include<string.h> #include<string> #include<cmath> #include<queue> #define LL long long using namespace std; int A,B,C; struct node { int n1,n2,tep; string a;//保存当前的操作 }; bool vis[100][100]; char str[6][10]= {"FILL(1)","FILL(2)","POUR(2,1)","POUR(1,2)","DROP(1)","DROP(2)"};//具体有六种实现 void bfs() { queue<node>q; while(!q.empty()) q.pop(); node f1,f2; int t; f1.n1=0; f1.n2=0; f1.tep=0; f1.a="";开始时为空串 q.push(f1); while(!q.empty()) { f1=q.front(); q.pop(); if(vis[f1.n1][f1.n2])//剪纸 continue; else vis[f1.n1][f1.n2]=true; if(f1.n1==C||f1.n2==C) { printf("%d\n",f1.tep); for(int j=0;j<f1.tep;j++) { printf("%s\n",str[ f1.a[j]-'0' ]);//分别对应到str中 } return ; } for(int i=0;i<4;i++) { f2=f1; f2.tep++; if(i==0) { if(f2.n1==0) { f2.n1=A; f2.n2=f1.n2;//注意这里必须是f2.x=f1.x因为不是的话可能会对下一个if()造成影响,尽管开头的部分有f2=f1;在下边并列的部分就无所谓了 f2.a=f1.a+'0'; q.push(f2); } if(f2.n2==0) { f2.n2=B; f2.n1=f1.n1;//保持相对不变 f2.a=f1.a+'1'; q.push(f2); } } if(i==1) { if(f2.n1!=0) { f2.n1=0; f2.n2=f1.n2; f2.a=f1.a+'4'; q.push(f2); } if(f2.n2!=0) { f2.n2=0; f2.n1=f1.n1; f2.a=f1.a+'5'; q.push(f2); } } if(i==3) { if(f2.n2!=0&&f2.n1!=A) { t=A-f2.n1; if(f2.n2>=t) { f2.n2-=t; f2.n1=A; } else { f2.n1+=f2.n2; f2.n2=0; } f2.a+='2'; q.push(f2); } } if(i==2) { if(f2.n1!=0&&f2.n2!=B) { t=B-f2.n2; if(f2.n1>=t) { f2.n1-=t; f2.n2=B; } else { f2.n2+=f2.n1; f2.n1=0; } f2.a+='3'; q.push(f2); } } } } printf("impossible\n"); } int main() { int n,m,i,j,k,s; while(~scanf("%d%d%d",&A,&B,&C)) { memset(vis,false,sizeof(vis)); bfs(); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/grit_icpc/article/details/47722331