bfs搜索,每个状态可以转移到6个新的状态,已经搜过的不再入队
AC代码:
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
const int INF=0x3f3f3f3f,MAXN=1000000000+7;
int vis[10000],mod[1000000],cnt,row[15],m,n,ans=-1;
typedef long long LL;
map<pair<int,int>,int> S;
char str[7][10]={"","FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(2,1)","POUR(1,2)"};
int A,B,C;
struct node{
pair<int,int> sta;
string x;
node(pair<int,int> a,string b){ sta=a; x=b; }
};
node chan(node x,int ind){
node t(x.sta,x.x);
t.x+=('0'+ind);
if (ind==1) t.sta.first=A;
else if (ind==2) t.sta.second=B;
else if (ind==3) t.sta.first=0;
else if (ind==4) t.sta.second=0;
else if (ind==5) {
int u=min(A-t.sta.first,t.sta.second);
t.sta.second-=u; t.sta.first+=u;
}
else {
int u=min(t.sta.first,B-t.sta.second);
t.sta.first-=u; t.sta.second+=u;
}
return t;
}
int main(){
scanf("%d%d%d",&A,&B,&C);
queue<node> que;
que.push(node(make_pair(0,0),""));
S[make_pair(0,0)]=1;
string ans;
while (!que.empty()){
node t=que.front();que.pop();
//cout<<t.x<<endl;
if (t.sta.first==C||t.sta.second==C) {
ans=t.x;
break;
}
for (int i=1;i<=6;i++){
node u=chan(t,i);
if (S.count(u.sta)) continue;
que.push(u);
S[u.sta]=1;
}
}
if (ans!="") {
printf("%d\n",ans.length());
for (int i=0;i<ans.length();i++){
printf("%s\n",str[ans[i]-'0']);
}
}
else printf("impossible\n");
}