POJ 3414 (BFS)

来源:互联网 发布:ipad1不支持新软件 编辑:程序博客网 时间:2024/06/09 19:49

题目链接:http://poj.org/problem?id=3414

题意:给出三个容器,各有容量A,B,C

有以下三种方式:

①:装满i

②:清空i

③把i倒入j中,直至倒满,否则全部全部倒入

只要模拟这6中操作就可以了...

难点在与打印路径..用map做一个该层与上一层的映射。

只能感慨自己写的代码丑到爆了..

最后参考了discuss里面的代码...

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<queue>#include<map>using namespace std;const int INF=0x3f3f3f3f;const int maxn=1010;int T,n;int A,B,C;bool flag;struct node{int x,y;string s;bool operator<(node a) const{return x<a.x||(x==a.x&&y<a.y);}};void Bfs(){string ans="";int sum=0;queue<node>q;map<node,node>m;node s,tmp;s.x=0,s.y=0,tmp.x=-1;m[s]=tmp;q.push(s);while(!q.empty()){s=q.front();q.pop();if(s.x==C||s.y==C){for(tmp=s;tmp.x||tmp.y;tmp=m[tmp])sum++,ans=tmp.s+"\n"+ans;cout<<sum<<endl<<ans;flag=true;return ;}tmp.x=A;tmp.y=s.y;tmp.s="FILL(1)";if(m.find(tmp)==m.end()) {q.push(tmp);m[tmp]=s;}tmp.x=s.x;tmp.y=B;tmp.s="FILL(2)";if(m.find(tmp)==m.end()) {q.push(tmp);m[tmp]=s;}tmp.x=0;tmp.y=s.y;tmp.s="DROP(1)";if(m.find(tmp)==m.end()) {q.push(tmp);m[tmp]=s;}tmp.x=s.x;tmp.y=0;tmp.s="DROP(2)";if(m.find(tmp)==m.end()) {q.push(tmp);m[tmp]=s;}tmp.x=min(s.x+s.y,A);tmp.y=max(0,s.x+s.y-A);tmp.s="POUR(2,1)";if(m.find(tmp)==m.end()) {q.push(tmp);m[tmp]=s;}tmp.x=max(0,s.x+s.y-B);tmp.y=min(s.x+s.y,B);tmp.s="POUR(1,2)";if(m.find(tmp)==m.end()) {q.push(tmp);m[tmp]=s;}}flag=false;}int main(){#ifndef ONLINE_JUDGE    freopen("test.in","r",stdin);    freopen("test.out","w",stdout);#endifwhile(~scanf("%d%d%d",&A,&B,&C)){Bfs();if(!flag) puts("impossible");}return 0;}


0 0