您的位置:首页 > 其它

POJ 3414 倒水(BFS+标记路径)

2018-02-27 20:49 281 查看
每日打卡(1/1)
传送门:点击打开链接
题目大意:
    瓶子1能装a升水,瓶子2能装b升水,问要装c升水最少要几步?

题解:
    明显的BFS,其中需要注意的地方就是记录路径。

    在结构体中设置一个node *pre,pre指向之前访问的操作,而结构体数组t也是BFS中一个比较新颖的操作。

代码:#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cmath>
#include<queue>
#include<stack>
#include<string>
using namespace std;
struct node{
int x,y,tot,flag;
node *pre;
}t[500];
stack<int> p;
int a,b,C,vis[110][110],counti = -1;

int bfs()
{
memset(vis,0,sizeof(vis));
node c;
queue<node> q;
c.x = 0;
c.y = 0;
c.tot = 0;
c.pre = NULL;
q.push(c);
vis[c.x][c.y] = 1;

while(!q.empty())
{
t[++counti] = q.front();
// cout<<t[counti].x<<" "<<t[counti].y<<endl;
q.pop();
for(int i=0;i<6;i++)
{
switch(i)
{
case 0:
c.x = a;
c.y = t[counti].y;
c.flag = 1;
break;
case 1:
c.x = t[counti].x;
c.y = b;
c.flag = 2;
break;
case 2:
c.x = 0;
c.y = t[counti].y;
c.flag = 3;
break;
case 3:
c.x = t[counti].x;
c.y = 0;
c.flag = 4;
break;
case 4:
if(t[counti].x>b-t[counti].y) {
c.y = b;
c.x = t[counti].x-(b-t[counti].y);
c.flag = 5;
}
else {
c.y = t[counti].x+t[counti].y;
c.x = 0;
c.flag = 5;
}
break;
case 5:
if(t[counti].y>a-t[counti].x) {
c.x = a;
c.y = t[counti].y-(a-t[counti].x);
c.flag = 6;
}
else {
c.x = t[counti].x+t[counti].y;
c.y = 0;
c.flag = 6;
}
break;
}
// cout<<c.x<<" "<<c.y<<endl;
if(!vis[c.x][c.y]) {
vis[c.x][c.y] = 1;
c.tot = t[counti].tot+1;
c.pre = &t[counti];
if(c.x==C||c.y==C) {
cout<<c.tot<<endl;
while(c.pre)
{
p.push(c.flag);
c = *c.pre;
}
while(!p.empty())
{
int flag = p.top();
p.pop();
switch(flag)
{
case 1:
cout<<"FILL(1)"<<endl;
break;
case 2:
cout<<"FILL(2)"<<endl;
break;
case 3:
cout<<"DROP(1)"<<endl;
break;
case 4:
cout<<"DROP(2)"<<endl;
break;
case 5:
cout<<"POUR(1,2)"<<endl;
break;
case 6:
cout<<"POUR(2,1)"<<endl;
break;
}
}
return 1;
}
q.push(c);
}
}
}
return 0;
}

int main()
{
cin>>a>>b>>C;
int ans = bfs();
if(!ans) {
cout<<"impossible"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: