其他分享
首页 > 其他分享> > POJ1606 Jugs

POJ1606 Jugs

作者:互联网

解法一:\(BFS\)

每次扩展的状态有\(6\)个。宽搜多写写还是有好处的。

const int N=110;
struct Node
{
    int ca,cb;
    int dist;
    string path;
};
bool vis[N][N];
string op[]={"FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
int ca,cb,target;

bool bfs()
{
    queue<Node> q;
    q.push({0,0,0,""});

    while(q.size())
    {
        Node t=q.front();
        q.pop();

        if(t.ca == target || t.cb == target)
        {
            cout<<t.dist<<endl;
            for(int i=0;i<t.path.size();i++)
            {
                int k=t.path[i]-'0';
                cout<<op[k]<<endl;
            }
            return true;
        }

        if(t.ca < ca && !vis[ca][t.cb])
        {
            vis[ca][t.cb]=true;
            q.push({ca,t.cb,t.dist+1,t.path+'0'});
        }

        if(t.cb < cb && !vis[t.ca][cb])
        {
            vis[t.ca][cb]=true;
            q.push({t.ca,cb,t.dist+1,t.path+'1'});
        }

        if(t.ca && !vis[0][t.cb])
        {
            vis[0][t.cb]=true;
            q.push({0,t.cb,t.dist+1,t.path+'2'});
        }

        if(t.cb && !vis[t.ca][0])
        {
            vis[t.ca][0]=true;
            q.push({t.ca,0,t.dist+1,t.path+'3'});
        }

        if(t.ca && t.cb < cb)
        {
            int na,nb;
            if(t.ca + t.cb > cb) na=t.ca+t.cb-cb, nb=cb;
            else na=0, nb=t.ca+t.cb;

            if(!vis[na][nb])
            {
                vis[na][nb]=true;
                q.push({na,nb,t.dist+1,t.path+'4'});
            }
        }

        if(t.cb && t.ca < ca)
        {
            int na,nb;
            if(t.ca + t.cb > ca) na=ca, nb=t.ca+t.cb-ca;
            else na=t.ca+t.cb, nb=0;

            if(!vis[na][nb])
            {
                vis[na][nb]=true;
                q.push({na,nb,t.dist+1,t.path+'5'});
            }
        }
    }
    return false;
}

int main()
{
    cin>>ca>>cb>>target;

    if(!bfs()) puts("impossible");

    //system("pause");
}

标签:Jugs,int,cb,nb,vis,na,POJ1606,ca
来源: https://www.cnblogs.com/fxh0707/p/14443465.html