傳送門(請點擊題目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
Sample Output 6 FILL(2) POUR(2,1) DROP(1) POUR(2,1) FILL(2) POUR(2,1)
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);
}