题解
2025-08-16 21:21:18
发布于:广东
4阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
int n,m,k;
bool vis[205][205]; //标记是否出现过
struct node
{
int a,b; //当前第一个桶和第二个桶的储水量
vector<string> opt; //操作序列
};
vector<string> qstr(vector<string> opt,string type,int a,int b) //转换成操作序列,注意fill和drop操作不需要第四个参数
{
string s="",t="";
s+=a+'0'; t+=b+'0';
if (type=="FILL" || type=="DROP")
opt.push_back(type+"("+s+")");
else
opt.push_back("POUR("+s+","+t+")");
return opt;
}
void bfs()
{
queue<node> q;
node tmp; tmp.a=0,tmp.b=0;
q.push(tmp);
vis[0][0]=1;
while (!q.empty())
{
int na=q.front().a,nb=q.front().b;
vector<string> nopt=q.front().opt;
if (na==k || nb==k) //找到了
{
cout << nopt.size() << endl;
for (auto v:nopt)
cout << v << endl;
return;
}
q.pop();
if (vis[n][nb]==0 && na<n) //fill(1,2),检查na小于n,避免无效操作
{
vis[n][nb]=1;
q.push(node{n,nb,qstr(nopt,"FILL",1,2)});
}
if (vis[na][m]==0 && nb<m)
{
vis[na][m]=1;
q.push(node{na,m,qstr(nopt,"FILL",2,1)});
}
if (vis[0][nb]==0 && na>0)
{
vis[0][nb]=1;
q.push(node{0,nb,qstr(nopt,"DROP",1,2)});
}
if (vis[na][0]==0 && nb>0)
{
vis[na][0]=1;
q.push(node{na,0,qstr(nopt,"DROP",2,1)});
}
if (na>0 && nb<m) //倒水
{
int aa=na,bb=nb;
bb+=aa;
aa=0;
if (bb>m) aa+=bb-m,bb=m;
if (vis[aa][bb]==0)
{
vis[aa][bb]=1;
q.push(node{aa,bb,qstr(nopt,"POUR",1,2)});
}
}
if (nb>0 && na<n)
{
int aa=na,bb=nb;
aa+=bb;
bb=0;
if (aa>n) bb+=aa-n,aa=n;
if (vis[aa][bb]==0)
{
vis[aa][bb]=1;
q.push(node{aa,bb,qstr(nopt,"POUR",2,1)});
}
}
}
cout << "impossible"; //所有状态遍历完了还没找到就impossible
return;
}
int main()
{
cin >> n >> m >> k;
bfs();
return 0;
}
这里空空如也
有帮助,赞一个