pots 倒水问题(bfs)

来源:互联网 发布:图像算法工程师 编辑:程序博客网 时间:2024/06/05 06:05

点击打开链接 <----HDU

Problem Description

You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:

  1. FILL(i)        fill the pot i (1 ≤ i ≤ 2) from the tap;
  2. DROP(i)      empty the pot i to the drain;
  3. POUR(i,j)    pour from pot i to pot j; after this operation either the potj is full (and there may be some water left in the poti), or the poti is empty (and all its contents have been moved to the potj).

Write a program to find the shortest possible sequence of these operations that will yield exactlyC liters of water in one of the pots.

 

Input
<p>On the first and only line are the numbers <b>A</b>, <b>B</b>, and <b>C</b>. These are all integers in the range from 1 to 100 and <b>C</b>≤max(<b>A</b>,<b>B</b>).</p>
 

Output
<p>The first line of the output must contain the length of the sequence of operations <b>K</b>. The following <b>K</b> 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 ‘<b>impossible</b>’.</p>
 

Sample Input
3 5 4
 

Sample Output
6FILL(2)POUR(2,1)DROP(1)POUR(2,1)FILL(2)POUR(2,1)
 

//广搜 打印路径问题  //特别新的就是广搜打印出路径来了 //主要是怎么走理清思路,不要重复。 #if 0#include<iostream>#include<queue>using namespace std;struct go{int  x,y,t;string s;};int m,n,c;bool vis[105][105];bool flag=0;void sprint(string s){for(int i=0; i<s.size(); i++){if(s[i]=='1')cout<<"FILL(1)"<<endl;elseif(s[i]=='2')cout<<"FILL(2)"<<endl;elseif(s[i]=='3')cout<<"POUR(2,1)"<<endl;elseif(s[i]=='4')cout<<"POUR(1,2)"<<endl;elseif(s[i]=='5')cout<<"DROP(1)"<<endl;elseif(s[i]=='6')cout<<"DROP(2)"<<endl;}}void bfs(){queue<go> q;go p;p.t=1;p.x=m;p.y=0;p.s='1';q.push(p);p.t=1;p.x=0;p.y=n;p.s='2';q.push(p);while(!q.empty()){go now;now=q.front();q.pop(); if(now.x==c||now.y==c){cout<<now.t<<endl;sprint(now.s);flag=1;return;}if(now.x<m)                //自来水加水 {go a;a.x=m;a.y=now.y;if(vis[a.x][a.y]==0){a.t=now.t+1;vis[a.x][a.y]=1;a.s=now.s+'1';q.push(a);}if(now.y>0)         //水桶加水 {int cx=m-now.x;if(now.y>=cx){a.x=m;a.y=now.y-cx;}else{a.x=now.x+now.y;a.y=0;}if(vis[a.x][a.y]==0){a.t=now.t+1;vis[a.x][a.y]=1;a.s=now.s+'3';q.push(a);}}}if(now.y<n)       //自来水加水 {go a;a.x=now.x;a.y=n;if(vis[a.x][a.y]==0){a.t=now.t+1;vis[a.x][a.y]=1;a.s=now.s+'2';q.push(a);}if(now.x>0)    //水桶加水 {int cy=n-now.y;if(now.x>=cy){a.y=n;a.x=now.x-cy;}else{a.y=now.x+now.y;a.x=0;}if(vis[a.x][a.y]==0){a.t=now.t+1;vis[a.x][a.y]=1;a.s=now.s+'4';q.push(a);}}}if(now.x>0)     //倒水 {go a;a.x=0;a.y=now.y;if(vis[a.x][a.y]==0){a.t=now.t+1;vis[a.x][a.y]=1;a.s=now.s+'5';q.push(a);}}if(now.y>0)  //倒水 {go a;a.y=0;a.x=now.x;if(vis[a.x][a.y]==0){a.t=now.t+1;vis[a.x][a.y]=1;a.s=now.s+'6';q.push(a);}}}}int main(){cin>>m>>n>>c;vis[0][0]=1;bfs();if(flag==0){cout<<"impossible"<<endl;}}#endif