poj 3414 Pots(BFS)(简单题)

来源:互联网 发布:广联达软件配置要求 编辑:程序博客网 时间:2024/05/17 07:51

Pots
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11551 Accepted: 4900 Special Judge

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 ≤ ≤ 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 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

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

题意:

两个杯子,一个勺,两个杯子的水量通过勺子装水或倒水操作变化,求最初状态变化到最终状态所需最小步数。

思路:

bfs遍历,每次有6种变化,由最初状态变化到最终状态所需最小步数。

代码:

#include <stdio.h>#include <memory.h>#define MAX 10001typedef struct Node{int a,b,step,pre,flag;};int A,B,C;Node queue[MAX];bool visit[101][101];int path[MAX],index;void bfs(){memset(visit,false,sizeof(visit));int front=0,rear=0;Node cur,next;cur.a=0,cur.b=0,cur.pre=-1,cur.step=0;visit[0][0]=true;queue[rear++]=cur;while(front!=rear){cur=queue[front++];if(cur.a==C||cur.b==C) break;for(int i=0;i<6;i++){switch(i){case 0: next.a=A; next.b=cur.b; next.flag=0; break;case 1:next.a=cur.a; next.b=B; next.flag=1; break;case 2:next.a=0; next.b=cur.b; next.flag=2; break;case 3:next.a=cur.a; next.b=0; next.flag=3; break;case 4:if(B-cur.b<cur.a){next.a=cur.a+cur.b-B;next.b=B;next.flag=4;}else{next.a=0;next.b=cur.a+cur.b;next.flag=4;}break;default:if(A-cur.a<cur.b){next.a=A;next.b=cur.a+cur.b-A;next.flag=5;}else{next.a=cur.a+cur.b;next.b=0;next.flag=5;}}//遍历完由该状态可以到达的状态if(!visit[next.a][next.b]){next.step=cur.step+1;next.pre=front-1;//[front++]queue[rear++]=next;visit[next.a][next.b]=true;}}}if(front==rear) {printf("impossible/n"); return ;}index=0;for(int i=front-1;i>=0;){path[index++]=i;i=queue[i].pre;}printf("%d\n",queue[front-1].step);for(int i=index-1;i>=0;i--){switch(queue[path[i]].flag){case 0:printf("FILL(1)\n");break;case 1:printf("FILL(2)\n"); break;case 2:printf("DROP(1)\n"); break;case 3:printf("DROP(2)\n"); break;case 4:printf("POUR(1,2)\n"); break;case 5:printf("POUR(2,1)\n"); break;}}}int main(){scanf("%d %d %d",&A,&B,&C);bfs();return 0;}



0 0