传送门.
思路:
宽搜;
预处理倒水方式存进字符串数组,然后用下标去代替路径;
用结构体去存每一步的状态,并更新下一步;
分类讨论:
按题意分类即可;
需要注意的是1 -> 2的情况是,也有两种情况,一种是1 倒不满 2,另一种是1 可以倒满 2.
很巧妙的是用结构体去记录了路径,本来想写栈的;
相似题目:
QWQ
代码:
#include <iostream>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#include <queue>
#include <utility>
#include <stack>
#define me memset
using namespace std;
typedef long long ll;
typedef pair<int,int>PII;
const int N = 210;
const int null = 0x3f3f3f3f;
int a,b,c;
string str[6] = {"FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
bool st[N][N];
struct Edge
{
int u,v,step;
int path[N];
}edge;
void bfs()
{
queue<Edge> q;
edge.u = 0,edge.v = 0,edge.step = 0;
me(edge.path,-1,sizeof edge.path);
q.push(edge);
st[edge.u][edge.v] = true;
while(q.size())
{
// cout << "****" << endl;
Edge t = q.front();
q.pop();
if(t.u == c || t.v == c)
{
cout << t.step << endl;
for(int i = 1;i <= t.step;i ++)
{
cout << str[t.path[i]] << endl;
}
return;
}
if(t.u != a && !st[a][t.v])
{
Edge tt = t;
st[a][tt.v] = true;
tt.u = a;
tt.step ++;
tt.path[tt.step] = 0;
q.push(tt);
}
if(t.v != b && !st[t.u][b])
{
Edge tt = t;
st[tt.u][b] = true;
tt.v = b;
tt.step ++;
tt.path[tt.step] = 1;
q.push(tt);
}
if(t.u != 0 && !st[0][t.v])
{
Edge tt = t;
st[0][tt.v] = true;
tt.u = 0;
tt.step ++;
tt.path[tt.step] = 2;
q.push(tt);
}
if(t.v != 0 && !st[t.u][0])
{
Edge tt = t;
st[tt.u][0] = true;
tt.v = 0;
tt.step ++;
tt.path[tt.step] = 3;
q.push(tt);
}
//a -> b
if(t.u != 0 && t.v != b)
{
Edge tt=t;
int idx = b - tt.v;
if(idx >= tt.u)
{
if(!st[0][tt.u + tt.v])
{
st[0][tt.u + tt.v] = true;
tt.v += tt.u;
tt.u = 0;
tt.step ++;
tt.path[tt.step] = 4;
q.push(tt);
}
}
else
{
if(!st[t.u - idx][b])
{
st[tt.u - idx][b] = true;
tt.u -= idx;
tt.v = b;
tt.step ++;
tt.path[tt.step] = 4;
q.push(tt);
}
}
}
//b -> a
if(t.v != 0 && t.u != a)
{
Edge tt=t;
int idx = a - tt.u;
if(idx >= tt.v)
{
if(!st[tt.v + tt.u][0])
{
st[tt.v + tt.u][0] = true;
tt.u += tt.v;
tt.v = 0;
tt.step ++;
tt.path[tt.step] = 5;
q.push(tt);
}
}
else
{
if(!st[a][tt.v - idx])
{
st[a][tt.v - idx] = true;
tt.u = a;
tt.v -= idx;
tt.step ++;
tt.path[tt.step] = 5;
q.push(tt);
}
}
}
}
puts("impossible");
}
int main()
{
cin >> a >> b >> c;
bfs();
}