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");
}
posted @ 2021-02-24 19:52  Dazzling!  阅读(29)  评论(0编辑  收藏  举报