http://poj.org/problem?id=3414
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 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.
题意:
两个杯子容量A B
操作:装满其中一个,倒空其中一个,把一个杯子的水倒到另一个杯子(倒慢另一个或者倒空自己为止)
tip
bfs走一下。。。主要的是记录路径。。我分了两个数组,一个记录从上个到现在这个的操作是什么,另一个记录上一步的状态是什么。。
vis【】【】,表示两个杯子分别的装水量,不可能重复
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int,int> pii;
const int maxn = 1100;
int A,B,C,step[maxn][maxn],an[maxn];
bool vis[maxn][maxn];
pii pre[maxn][maxn];
pii sov(int step,int x,int y){
if(step == 1) x = A;
if(step == 2) y = B;
if(step == 3) x = 0;
if(step == 4) y = 0;
if(step == 5){
int ans = min(A-x,y);
x += ans;y-=ans;
}
if(step == 6){
int ans = min(x,B-y);
x -= ans;y += ans;
}
return make_pair(x,y);
}
void pr(int step){
if(step == 1) printf("FILL(1)\n");
if(step == 2) printf("FILL(2)\n");
if(step == 3) printf("DROP(1)\n");
if(step == 4) printf("DROP(2)\n");
if(step == 5) printf("POUR(2,1)\n");
if(step == 6) printf("POUR(1,2)\n");
}
void print(int x,int y){
int tot = 0;
while(!(x==0&&y==0)){
an[tot++] = step[x][y];
pii tmp = pre[x][y];
x = tmp.first;y = tmp.second;
}
printf("%d\n",tot);
for(int i = tot-1 ; i >= 0 ;i--){
pr(an[i]);
}
}
void bfs(){
queue<pii>q;
q.push(make_pair(0,0));
while(!q.empty()){
pii tmp = q.front();
q.pop();
if(tmp.first == C||tmp.second == C){
print(tmp.first,tmp.second);
return;
}
for(int i = 1 ; i <= 6 ; i++){
pii s = sov(i,tmp.first,tmp.second);
// printf("s.fi = %d , s.se = %d\n",s.first,s.second);
if(vis[s.first][s.second] == false){
vis[s.first][s.second] = true;
q.push(s);
pre[s.first][s.second] = tmp;
step[s.first][s.second] = i;
}
}
}
printf("impossible\n");
}
void init(){
memset(vis,false,sizeof(vis));
vis[0][0] = true;
bfs();
}
int main(){
while(~scanf("%d%d%d",&A,&B,&C))
init();
}