点击打开链接题目链接
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 9430 | Accepted: 3963 | 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)
题目大意是给两个容量分别为 A,B的杯子 只能在以下操作三选一
1 把某个杯子装满
2 把某个杯子倒光
3 把一个杯子中的水倒入另一个杯子
问最少几次能够在某个杯子中出现杯中水的量为C的情况 并且输出操作的各个步骤
先贴代码
#include<cstdio>
#include<cstring>
int a,b,fin;
int mark[110][110];
struct status
{
int x,y,pre,step,op;//pre:上次操作的位置(类似指针) op:进行的具体操作
}queue[100100],u,v;
int ope[1001];
int bfs()
{
int fr,ed;
int i;
fr=ed=0;
queue[0].x=0;
queue[0].y=0;
queue[0].step=0;
queue[0].op=100;
queue[0].pre=100;
ed++;
mark[0][0]=1;
while(fr<ed)
{
u=queue[fr++];
if(u.x==fin||u.y==fin)
{
int x=u.step;
for(i=x-1;i>=0;i--)//因为是从后面的操作到前面的操作 所以需要倒序
{
ope[i]=u.op;
u=queue[u.pre];
}
return x;
}
for(i=0;i<6;i++)
{
if(i==0)
{
v.x=a;
v.y=u.y;
}
else if(i==1)
{
v.x=u.x;
v.y=b;
}
else if(i==2)
{
v.x=0;
v.y=u.y;
}
else if(i==3)
{
v.x=u.x;
v.y=0;
}
else if(i==4)
{
if(u.x+u.y<=b)
{
v.x=0;
v.y=u.x+u.y;
}
else
{
v.x=u.x+u.y-b;
v.y=b;
}
}
else if(i==5)
{
if(u.x+u.y<=a)
{
v.x=u.x+u.y;
v.y=0;
}
else
{
v.x=a;
v.y=u.x+u.y-a;
}
}
v.op=i;
if(mark[v.x][v.y]==0)
{
v.step=u.step+1;
v.pre=fr-1;//把上次操作的位置保存到v中
queue[ed++]=v;
mark[v.x][v.y]=1;
}
}
}
return -1;
}
int main()
{
int t;
while(scanf("%d%d%d",&a,&b,&fin)!=EOF)
{
memset(mark,0,sizeof(mark));
t=bfs();
if(t==-1)
printf("impossible\n");
else
{
printf("%d\n",t);
for(int i=0;i<t;i++)
{
if(ope[i]==0)
printf("FILL(1)\n");
else if(ope[i]==1)
printf("FILL(2)\n");
else if(ope[i]==2)
printf("DROP(1)\n");
else if(ope[i]==3)
printf("DROP(2)\n");
else if(ope[i]==4)
printf("POUR(1,2)\n");
else if(ope[i]==5)
printf("POUR(2,1)\n");
}
}
}
return 0;
}
有一种单向链表的感觉