您的位置:首页 > 其它

POJ训练计划3414_Pots(BFS)

2014-06-05 18:11 435 查看
Pots

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9224 Accepted: 3882 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 ≤ ≤ 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 AB, 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)

Source
Northeastern Europe 2002, Western Subregion
解题报告
BFS。有点模拟的感觉,敲出答案了,就是记录路径不大会,看了大神的代码,就是在结构体多加了两个元素,一个说明他的操作,
另一个指向他的前一个。。。
MLE一次,队列开打了。。。
2A
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
struct node
{
int a,b,step,tp,nt;
}Q[100000];
int A,B,C,vis[110][110];
void print(int i)
{
if(i<=0)
{
return ;
}
print(Q[i].nt);
int t=Q[i].tp;
if(t==1)printf("FILL(1)\n");
else if(t==2)printf("FILL(2)\n");
else if(t==3)printf("DROP(1)\n");
else if(t==4)printf("DROP(2)\n");
else if(t==5)printf("POUR(1,2)\n");
else if(t==6)printf("POUR(2,1)\n");
}
void bfs()
{
node now,next;
int l=0,r=0,f=0;
now.a=0;
now.b=0;
now.step=0;
now.tp=0;
now.nt=0;
Q[r++]=now;
vis[0][0]=1;
while(l!=r)
{
now=Q[l];
if(now.a==C||now.b==C)
{
cout<<now.step<<endl;
f=1;
break;

}
for(int i=1;i<=6;i++)
{
if(i==1)//FILL(a)
{
next.a=A;
next.b=now.b;
}
else if(i==2)//FILL(b)
{
next.a=now.a;
next.b=B;
}
else if(i==3)//DROP(a)
{
next.a=0;
next.b=now.b;
}
else if(i==4)//DROP(b)
{
next.a=now.a;
next.b=0;
}
else if(i==5)//POUR(a,b)
{
next.a=(now.a-(B-now.b))>0?(now.a-(B-now.b)):0;
next.b=(now.b+now.a)>B?B:(now.b+now.a);
}
else if(i==6)//POUR(b,a)
{
next.a=(now.a+now.b)>A?A:(now.a+now.b);
next.b=(now.b-(A-now.a))>0?(now.b-(A-now.a)):0;
}
next.tp=i;
next.nt=l;
if(!vis[next.a][next.b])
{
next.step=now.step+1;
Q[r++]=next;
vis[next.a][next.b]=1;
}
}
l++;
}
if(f)
print(l);
else cout<<"impossible"<<endl;
}
int main()
{
int i,j;
while(cin>>A>>B>>C)
{
memset(vis,0,sizeof(vis));
memset(Q,0,sizeof(Q));
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: