传送门(请点击题目Pots)
Pots
Pots
Description You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
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 Source Northeastern Europe 2002, Western Subregion |
题意:
- 两锅1,2,他们分别装有a,b升水。我们可以进行以下三个操作(其实是六个)
- 把锅i(i=1或2)加满水。FILL(1)或FILL(2)
- 把 锅i 的水倒入 锅j 中,如果j满了,则不能再继续倒水。POUR(1,2)或POUR(2,1)
- 把锅i 的水倒掉。DROP(1)或DROP(2)
- 一共六个操作,直接bfs就好了,代码很清晰易懂的。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<set>
#include<algorithm>
#define sc(x) scanf("%d",&x)
#define scc(x,y) scanf("%d%d",&x,&y)
#define scll(x) scanf("%lld",&x)
#define mem(x,a) memset(x,a,sizeof x)
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1005;
string op[]={"FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
bool vis[maxn][maxn];
struct pot{
int a,b; //当前1,2中的水量
vector<int> sq; // 记录路径
};
void bfs(int a,int b,int c){
vis[a][b]=1;
mem(vis,0);
queue<pot> Q;
pot t;
t.a = t.b =0;
t.sq.clear();
vis[0][0]=1;
Q.push(t);
while(!Q.empty()){
pot f = Q.front();
Q.pop();
if(f.a==c || f.b==c){
cout<<f.sq.size()<<endl;
for(int i=0;i<f.sq.size();i++){
cout<<op[f.sq[i]]<<endl;
}
return;
}
pot tmp;
for(int i=0;i<6;i++){
if(i==0){ // FILL(1)
tmp.a=a;
tmp.b=f.b;
}
if(i==1){ //FILL(2)
tmp.b=b;
tmp.a = f.a;
}
if(i==2){ // DROP(1)
tmp.a=0;
tmp.b=f.b;
}
if(i==3){ // DROP(2)
tmp.a=f.a;
tmp.b=0;
}
if(i==4){ // POUR(1,2)
if(f.a > b-f.b){
tmp.b = b;
tmp.a = f.a-(b-f.b);
}
else{
tmp.a=0;
tmp.b=f.a+f.b;
}
}
if(i==5){ // POUR(2,1)
if(f.b > a-f.a){
tmp.a = a;
tmp.b = f.b-(a-f.a);
}
else{
tmp.b=0;
tmp.a=f.b+f.a;
}
}
if(!vis[tmp.a][tmp.b]){ //没有到达的状态,更新入队
vis[tmp.a][tmp.b]=1;
tmp.sq.assign(f.sq.begin(),f.sq.end());//把路径赋值给下一个要进行入队的状态
tmp.sq.push_back(i); // 把当前的操作路径在放进当前要放进队列状态中
Q.push(tmp);
}
}
}
printf("impossible\n");
}
int main(){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
bfs(a,b,c);
}