POJ - 3414 Pots(BFS)

题目链接

题意:两个盆,一个最多能装a体积水,另一个能装b体积水。
有三种操作:
1、把其中一盆水装满
2、把其中一盆水倒掉
3、把其中一盆水倒入另外一盆水中,如果超过了当前盆的容量,则只倒到盆的最大容量。

三种操作分为6种状态,a加满,b加满,b倒入a,a倒入b,a倒掉,b倒掉。bfs遍历。在结构体中吧两盆水的体积,操作次数和操作状态记录下来,vis数组记录已经用过的状态。

#include<iostream>
#include<queue>
#include<string>
using namespace std;
int a,b,c,ans;
int vis[105][105];
struct node{
    int x,y,num;
    string s;
};
char str[10][10]={"0","FILL(1)","FILL(2)","POUR(2,1)","POUR(1,2)","DROP(1)","DROP(2)"};
void check(){

}

string bfs(){
    node st,ne;
    st.x=0,st.y=0,st.num=0;
    vis[st.x][st.y]=1;
    queue<node>q;
    q.push(st);
    while(!q.empty()){
        //cout<<st.x<<' '<<st.y<<endl;
        st=q.front();
        q.pop();
        ne.num=st.num+1;

        ne.x=a,ne.y=st.y;
        ne.s=st.s+'1';
        if(ne.x==c||ne.y==c){
            ans=ne.num;
            return ne.s;
        }
        if(!vis[ne.x][ne.y]){
            vis[ne.x][ne.y]=1;
            q.push(ne);
        }

        ne.x=st.x,ne.y=b;
        ne.s=st.s+'2';
        if(ne.x==c||ne.y==c){
            ans=ne.num;
            return ne.s;
        }
        if(!vis[ne.x][ne.y]){
            vis[ne.x][ne.y]=1;
            q.push(ne);
        }

        ne.x=min(st.x+st.y,a);
        ne.y=st.y-(ne.x-st.x);
        ne.s=st.s+'3';
        if(ne.x==c||ne.y==c){
            ans=ne.num;
            //cout<<ne.x<<' '<<ne.y<<endl;
            return ne.s;
        }
        if(!vis[ne.x][ne.y]){
            vis[ne.x][ne.y]=1;
            q.push(ne);
        }

        ne.y=min(st.y+st.x,b);
        ne.x=st.x-(ne.y-st.y);
        ne.s=st.s+'4';
        if(ne.x==c||ne.y==c){
            ans=ne.num;
            return ne.s;
        }
        if(!vis[ne.x][ne.y]){
            vis[ne.x][ne.y]=1;
            q.push(ne);
        }

        ne.x=0,ne.y=st.y;
        ne.s=st.s+'5';
        if(ne.x==c||ne.y==c){
            ans=ne.num;
            return ne.s;
        }
        if(!vis[ne.x][ne.y]){
            vis[ne.x][ne.y]=1;
            q.push(ne);
        }
        ne.x=st.x,ne.y=0;
        ne.s=st.s+'6';
        if(ne.x==c||ne.y==c){
            ans=ne.num;
            return ne.s;
        }
        if(!vis[ne.x][ne.y]){
            vis[ne.x][ne.y]=1;
            q.push(ne);
        }
    }
    return "0";
}

int main(){
    cin>>a>>b>>c;
    ans=-1;
    string x=bfs();
    if(ans==-1) cout<<"impossible"<<endl;
    else{
        cout<<ans<<endl;
        for(int i=0;i<x.size();i++){
            cout<<str[x[i]-'0']<<endl;
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值