| Time Limit: 1000MS | Memory Limit: 65536K | |||
| Total Submissions: 15043 | Accepted: 6328 | 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)
Source
#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct node{
int a,b,step;
string s;
}p,q;
int A,B,C;
int Map[101][101];
int bfs()
{
queue<node>qq;
Map[0][0]=1;
p.a=p.b=p.step=0;
qq.push(p);
while(!qq.empty())
{
p=qq.front();
qq.pop();
if(p.a==C||p.b==C)
return 1;
int aa,bb;
for(int i=1;i<=6;i++)
{
if(i==1)
aa=A,bb=p.b;
else if(i==2)
aa=p.a,bb=B;
else if(i==3)
{
if(p.a+p.b>A)
bb=p.a+p.b-A,aa=A;
else
aa=p.a+p.b,bb=0;
}
else if(i==4)
{
if(p.a+p.b>B)
bb=B,aa=p.a+p.b-B;
else
bb=p.a+p.b,aa=0;
}
else if(i==5)
{
aa=0,bb=p.b;
}
else
aa=p.a,bb=0;
if(Map[aa][bb]==0)
{
Map[aa][bb]=1;
q.a=aa;
q.b=bb;
q.step=p.step+1;
char c=i+'0';
q.s="";
q.s+=p.s+c;
qq.push(q);
}
}
}
return 0;
}
void print(char ch)
{
if(ch=='1')
puts("FILL(1)");
else if(ch=='2')
puts("FILL(2)");
else if(ch=='3')
puts("POUR(2,1)");
else if(ch=='4')
puts("POUR(1,2)");
else if(ch=='5')
puts("DROP(1)");
else
puts("DROP(2)");
}
int main()
{
while(cin>>A>>B>>C)
{
memset(Map,0,sizeof(Map));
if(bfs())
{
printf("%d\n",p.step);
for(int i=0;i<p.step;i++)
print(p.s[i]);
}
else
{
printf("impossible\n");
}
}
return 0;
}
本文介绍了一个经典的两桶水问题,并提供了一种通过广度优先搜索算法来寻找从初始状态到目标状态最短操作路径的方法。该算法适用于任意两个不同容量的桶,能够输出达到特定水量所需的最少步骤及具体操作。
1771

被折叠的 条评论
为什么被折叠?



