POJ

来源:互联网 发布:mac键盘部分按键失灵 编辑:程序博客网 时间:2024/06/05 08:27

POJ - 3414 Pots

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 potj; after this operation either the pot j is full (and there may be some water left in the poti), or the pot i 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

On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 andC≤max(A,B).

    Output

The first line of the output must contain the length of the sequence of operationsK. 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,3种操作,FILL(i),是把第I个锅填满,DROP(i),是把第I个锅清空,POUR(i,j)是把第i个锅的水倒入第j个锅,要么前者空,要么后者满。问需要多少操作得到有着C体积的水


和非常可乐那道题一样,广度优先搜索,每一口锅有三种操作,两口锅,每一次扩展即有6种操作,用一个二维数组记录两口锅的状态,不同的是这道题需要记录每一种操作,最后输出,这里用了一个pre变量来记录上一次的信息

#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<algorithm>using namespace std;const int maxn=110;string op[7]={" ","FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(2,1)","POUR(1,2)"};int l,r;int a,b,c;int vis[maxn][maxn],step[maxn*maxn]; struct node{int x,y;int opr;int pre;}info[maxn*maxn];void print(){int ans=0;while(l!=0){step[ans++]=info[l].opr;l=info[l].pre;}printf("%d\n",ans);for(int i=ans-1;i>=0;i--)   cout<<op[step[i]]<<endl;}void solve(int x,int y,int opr){if(vis[x][y]) return;vis[x][y]=1;info[r].x=x;info[r].y=y;info[r].opr=opr;info[r].pre=l;r++;}void bfs(){info[0].x=0;info[0].y=0;vis[0][0]=1;l=0;r=1;int tx,ty;while(l!=r){if(info[l].x==c||info[l].y==c){print();return;}tx=a;ty=info[l].y;solve(tx,ty,1);tx=info[l].x;ty=b;solve(tx,ty,2);tx=0;ty=info[l].y;solve(tx,ty,3);tx=info[l].x;ty=0;solve(tx,ty,4);tx=info[l].x+min(a-info[l].x,info[l].y);ty=info[l].y-min(a-info[l].x,info[l].y);solve(tx,ty,5);tx=info[l].x-min(info[l].x,b-info[l].y);ty=info[l].y+min(b-info[l].y,info[l].x);solve(tx,ty,6);l++;}if(l>=r) printf("impossible\n");}int main(void){while(scanf("%d%d%d",&a,&b,&c)!=EOF){memset(vis,0,sizeof(vis));bfs();}return 0;} 

非常可乐那道题  http://blog.csdn.net/gyh0730/article/details/76364999