Poj 3414 Pots (BFS+回溯+队列)

3414 -- Pots (poj.org)

这道题需要输出最后结果的执行过程,可以通过结构体,在结构体中定义一个数组s,s中存储了每一步的执行过程,实现了回溯。并且在运行中可以适当剪枝,减少枚举次数。

#include<iostream> 
#include<queue>
#include<cstring>
using namespace std;
const int N=110;
int aa,bb,cc,vis[N][N];
struct node{
    int a,b,step,s[N];
};
void BFS(){
    memset(vis,0,sizeof(vis));
    queue<node> q;
    node start;
    start.a=0;
    start.b=0;
    start.step=0;
    vis[start.a][start.b]=1;
    q.push(start);
    while(!q.empty()){
        start=q.front();
        q.pop();
        if(start.a==cc || start.b==cc){
            cout<<start.step<<endl;
            for(int i=0;i<start.step;i++){
                switch(start.s[i]){
                    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 ;
        }else{
            node next;
            for(int i=1;i<=6;i++){
                next=start;
                next.s[next.step++]=i;
                if(i==1 && next.a!=aa) next.a=aa;
                else if(i==2 && next.b!=bb)next.b=bb;
                else if(i==3 && next.a) next.a=0;
                else if(i==4 && next.b) next.b=0;
                else if(i==5 && next.a && next.b!=bb){
                    if(next.a+next.b>bb){
                        next.a=next.a+next.b-bb;
                        next.b=bb;
                    }else{
                        next.b=next.a+next.b;
                        next.a=0;
                    }
                }else if(i==6 && next.b && next.a!=aa){
                    if(next.a+next.b>aa){
                        next.b=next.a+next.b-aa;
                        next.a=aa;
                    }else{
                        next.a=next.a+next.b;
                        next.b=0;
                    }
                }
                if(vis[next.a][next.b]) continue;
                vis[next.a][next.b]=1;
                q.push(next); 
            }    
        }
    }
    cout<<"impossible"<<endl;
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>aa>>bb>>cc;
    BFS();
    return 0;
}

 

posted @ 2024-02-03 14:35  ACCbulb  阅读(25)  评论(0)    收藏  举报