poj 3414 Pots(bfs)

第一次做的时候,我定义了一个结构体,用来表示一个壶,后来搜索的时候发现无法从壶之前的状态转移到现在的状态,这就尴尬了。然后去看了一下别人的题解,就ac了。
思路:一共有三种操作,两个壶,共六种操作,直接对这六种操作bfs,这个很好想。主要是我看的别人题解是把两个壶的状态保存在同一个结构体里。

最后搜索完做好标记递归输出就好

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int a,b,c;
int book[101][101];

struct Pot
{
    int a,b,step,par;
    string op;
};

Pot que[5000];
int index;

void calc(Pot& p,Pot& cur,int& tail, int head)
{
    if(book[cur.a][cur.b] == 0)
    {
        cur.step = p.step + 1;
        cur.par = head;
        que[tail++] = cur;
        book[cur.a][cur.b] = 1;
    }
}

bool BFS()
{
    int head = 0;
    int tail = 0;
    que[tail].a = que[tail].b = que[tail].step = 0;
    que[tail].par = -1;
    ++tail;
    book[0][0] = 1;
    while(head < tail)
    {
        Pot p = que[head++];
        if(p.a == c || p.b == c)
        {
            cout << p.step << endl;
            index = head - 1;
            return true;
        }
        Pot cur;

        cur.a = a;
        cur.b = p.b;
        cur.op = "FILL(1)";
        calc(p,cur,tail,head-1);

        cur.a = p.a;
        cur.b = b;
        cur.op = "FILL(2)";
        calc(p,cur,tail,head-1);

        cur.a = 0;
        cur.b = p.b;
        cur.op = "DROP(1)";
        calc(p,cur,tail,head-1);

        cur.a = p.a;
        cur.b = 0;
        cur.op = "DROP(2)";
        calc(p,cur,tail,head-1);

        cur.b = p.b + p.a;
        cur.a = p.a - (b - p.b);
        cur.op = "POUR(1,2)";
        if(cur.b > b) cur.b = b;
        if(cur.a < 0) cur.a = 0;
        calc(p,cur,tail,head-1);

        cur.a = p.a + p.b;
        cur.b = p.b - (a - p.a);
        cur.op = "POUR(2,1)";
        if(cur.a > a) cur.a = a;
        if(cur.b < 0) cur.b = 0;
        calc(p,cur,tail,head-1);

    }
    cout << "impossible" <<endl;
    return false;
}

void Print(int index)
{
    if(que[index].par == -1) return;
    Print(que[index].par);
    cout << que[index].op << endl;
}

int main()
{
    while(cin >> a >> b >> c)
    {
        index = 0;
        memset(book,0,sizeof(book));
        if(BFS()) Print(index);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值