题目链接
思路:
结构体中建立一个路径数组,用来记录路径,满足要求输出,其他就和简单bfs一样,注意分类讨论六种操作
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define x first
#define y second
#define fi first
#define se second
#define pb push_back
#define pf push_front
#define PI acos(-1)
#define fast ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int>PII;
typedef pair<double,double>PDD;
typedef pair<PII,int>PIII;
typedef set<int>::iterator SIT;
int gcd(int a,int b) {return b?gcd(b,a%b):a;}
int lcm(int a,int b) {return a/gcd(a,b)*b;}
const double eps=1e-6;
const int INF=0x3f3f3f3f,mod=1e9+7;
const int N=110;
int a,b,c;
string print[6]={"FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
bool st[N][N];
struct node{
int x,y;
int cnt;
int path[10010];
};
void bfs(){
queue<node>q;
memset(st,0,sizeof(st));
node t;
t.x=0,t.y=0,t.cnt=0;
memset(t.path,-1,sizeof(t.path));
q.push(t);
st[t.x][t.y]=1;
while(q.size()){
node t=q.front();
q.pop();
if(t.x==c||t.y==c){
cout<<t.cnt<<endl;
for(int i=0;i<t.cnt;i++) cout<<print[t.path[i]]<<endl;
return;
}
for(int i=0;i<6;i++){
node now=t;
now.cnt++;
if(i==0&&now.x!=a){//装满a
now.x=a;
if(!st[now.x][now.y]){
st[now.x][now.y]=1;
now.path[t.cnt]=0;
q.push(now);
}
}
else if(i==1&&now.y!=b){//装满b
now.y=b;
if(!st[now.x][now.y]){
st[now.x][now.y]=1;
now.path[t.cnt]=1;
q.push(now);
}
}
else if(i==2&&now.x!=0){//倒掉a
now.x=0;
if(!st[now.x][now.y]){
st[now.x][now.y]=1;
now.path[t.cnt]=2;
q.push(now);
}
}
else if(i==3&&now.y!=0){//倒掉b
now.y=0;
if(!st[now.x][now.y]){
st[now.x][now.y]=1;
now.path[t.cnt]=3;
q.push(now);
}
}
else if(i==4){//将a倒进b
if(now.x+now.y>b){//如果能倒满b
now.x-=b-now.y;
now.y=b;
}
else{//如果倒不满b
now.y+=now.x;
now.x=0;
}
if(!st[now.x][now.y]){
st[now.x][now.y]=1;
now.path[t.cnt]=4;
q.push(now);
}
}
else if(i==5){//将b倒进a
if(now.x+now.y>a){//如果能倒满a
now.y-=a-now.x;
now.x=a;
}
else{//如果倒不满b
now.x+=now.y;
now.y=0;
}
if(!st[now.x][now.y]){
st[now.x][now.y]=1;
now.path[t.cnt]=5;
q.push(now);
}
}
}
}
cout<<"impossible"<<endl;
}
int main(){
cin>>a>>b>>c;
bfs();
return 0;
}