題目連接:http://poj.org/problem?id=3414ios
Time Limit: 1000MS Memory Limit: 65536Kthis
Descriptionspa
You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:3d
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.code
Inputorm
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).blog
Outputip
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’.ci
Sample Inputget
3 5 4
Sample Output
6
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)
題意:
給出兩個容積分別爲 $A,B$ 的壺,現有三種操做:
給出目標 $C$,要求最終至少某一個壺中的水量正好爲 $C$,要求輸出最少步數。
題解:
暴力搜索。
AC代碼:
#include<cstdio> #include<cstring> #include<iostream> #include<string> #include<queue> using namespace std; typedef pair<int,int> pii; int A,B,C; string op[7]={"","FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"}; inline pii change(pii x,int type) { int a=x.first, b=x.second; switch(type) { case 1: //倒滿a a=A; break; case 2: //倒滿b b=B; break; case 3: //倒空a a=0; break; case 4: //倒空b b=0; break; case 5: //a倒到b if(a>=B-b) a-=B-b, b=B; else b+=a, a=0; break; case 6: //b倒到a if(b>=A-a) b-=A-a, a=A; else a+=b, b=0; break; } return make_pair(a,b); } int vis[105][105]; pii pre[105][105]; queue<pii> Q; inline pii bfs() { memset(vis,0,sizeof(vis)); memset(pre,0,sizeof(pre)); Q.push(make_pair(0,0)); vis[0][0]=1; while(!Q.empty()) { pii now=Q.front(); Q.pop(); if(now.first==C || now.second==C) return now; for(int type=1;type<=6;type++) { pii nxt=change(now,type); if(!vis[nxt.first][nxt.second]) { vis[nxt.first][nxt.second]=type; pre[nxt.first][nxt.second]=now; Q.push(nxt); } } } return make_pair(-1,-1); } int main() { cin>>A>>B>>C; pii x=bfs(); if(x.first==-1 && x.second==-1) printf("impossible\n"); else { vector<int> ans; while(x.first+x.second>0) { ans.push_back(vis[x.first][x.second]); x=pre[x.first][x.second]; } printf("%d\n",ans.size()); for(int i=ans.size()-1;i>=0;i--) cout<<op[ans[i]]<<endl; } }