BFS+路径记录
大致题意:有A和B两个杯子,告诉你A和B的容量(互质)和目标容量V,让你求倒到V的过程。
思路:
这种状态转移的题目基本就是两种思路——搜索或者DP
这题一共有六种转移方式:
fill
1、A不满 倒满
2、B不满 倒满
empty
3、A不空 倒空
4、B不空 倒空
pour
5、B不满 A不空 A->B (B满 or A空)
6、A不满 B不空 B->A (A满 or B空)
知道这六种转移的方式后bfs就可以找到所需的目标容量V。
But
这里需要记录路径,这题不像A题可以直接用个数组记录前驱,我们可以用一个结构体记录状态,在结构体中可以设置一个队列记录到达这个状态进行的操作,这里我们用1~6表示六种不同的操作。
#include<iostream>
#include<cstring>
#include<queue>
#define llong long long
#define For(i,a,n) for(register int i=a;i<=n;i++)
#define RF(i,a,n) for(register int i=a;i>=n;i--)
#define inf 1e9
#define maxn 100005
#pragma GCC optimize(2)
using namespace std;
//存状态
struct status
{
int a, b; // a b是A和B当前水量
queue<int> ans; //记录路径
//构造函数
status() {}
status(int x,int y):a(x),b(y) {}
status(const status& pre):a(pre.a),b(pre.b),ans(pre.ans) {}
status(const status& pre,int x,int y):a(x),b(y),ans(pre.ans) {}
};
int Va, Vb, V; //Va为A的容量 Vb为B的容量 V为目标容量
int vis[1005][1005]; //状态是否访问过
void output(int num)
{
switch(num)
{
case 1:
cout<<"fill A"<<endl; break;
case 2:
cout<<"fill B"<<endl; break;
case 3:
cout<<"empty A"<<endl; break;
case 4:
cout<<"empty B"<<endl; break;
case 5:
cout<<"pour A B"<<endl; break;
case 6:
cout<<"pour B A"<<endl; break;
}
}
void bfs()
{
memset(vis,0,sizeof(vis));
status s(0,0);
queue<status> Q; Q.push(s);
while(Q.size()){
status tmp = Q.front(); Q.pop();
int a = tmp.a, b = tmp.b;
//六种状态
if(a == V || b == V){ //bfs结束 倒到目标V
while(tmp.ans.size()){
int t = tmp.ans.front();
tmp.ans.pop();
output(t);
}
cout<<"success"<<endl;
break;
}
if(a != Va){ //1
status newS(tmp, Va, b);
newS.ans.push(1);
if(!vis[Va][b]){
Q.push(newS);
vis[Va][b] = 1;
}
}
if(b != Vb){ //2
status newS(tmp, a, Vb);
newS.ans.push(2);
if(!vis[a][Vb]){
Q.push(newS);
vis[a][Vb] = 1;
}
}
if(a){ //3
status newS(tmp, 0, b);
newS.ans.push(3);
if(!vis[0][b]){
Q.push(newS);
vis[0][b] = 1;
}
}
if(b){ //4
status newS(tmp, a, 0);
newS.ans.push(4);
if(!vis[a][0]){
Q.push(newS);
vis[a][0] = 1;
}
}
if(a && b != Vb){ //5
status newS(tmp);
(newS.a+newS.b)>Vb ?
(newS.a-=(Vb-newS.b),newS.b=Vb) :
(newS.b+=newS.a,newS.a=0);
newS.ans.push(5);
if(!vis[newS.a][newS.b]){
Q.push(newS);
vis[newS.a][newS.b]=1;
}
}
if(b && a != Va){ //6
status newS(tmp);
(newS.a+newS.b)>Va ?
(newS.b-=(Va-newS.a),newS.a=Va) :
(newS.a+=newS.b,newS.b=0);
//cout<<newS.a<<" "<<newS.b<<endl;
newS.ans.push(6);
if(!vis[newS.a][newS.b]){
Q.push(newS);
vis[newS.a][newS.b]=1;
}
}
}
}
int main(){
ios::sync_with_stdio(false);
while(cin>>Va>>Vb>>V){
bfs();
}
return 0;
}