http://poj.org/problem?id=3414
题目大意:两个可以装A升和B升的空瓶,通过以下操作得到C升的水。
1. 给瓶子装满水。
2. 将瓶子的水倒光。
3. 将其中一只瓶子的水倒给另一只瓶子(能全部倒就要全部倒,否则剩在瓶子中)。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
using namespace std;
int a,b,c,s;
struct Node
{
int a,b;//保存状态
int v,s,t;//步数,当前下标,之前的状态下标
string str;
Node(int a,int b,int c,int d,int f,string ch)
{
str=ch;
this->a=a;
this->b=b;
v=c;
s=d;
t=f;
}
}*head[10050];
int bfs()
{
if(a==c||b==c) return 1;
int n,i,j,v,m;
int use[101][101];//同一种状态延伸的状态相同,所以状态要唯一,否则无限搜索
memset(use,0,sizeof(use));
string str;
queue<Node*> q;
//初始化状态
head[0]=NULL;
str="FILL(1)";
head[1]=new Node(a,0,1,1,0,str);
q.push(head[1]);
str="FILL(2)";
head[2]=new Node(0,b,1,2,0,str);
q.push(head[2]);
n=3;
use[a][0]=1;
use[0][b]=1;
use[0][0]=1;
while(!q.empty())
{
i=q.front()->a;
j=q.front()->b;
v=q.front()->v;
m=q.front()->s;
q.pop();
//满水
if(i!=a&&!use[a][j])
{
str="FILL(1)";
use[a][j]=1;
head[n]=new Node(a,j,v+1,n,m,str);
q.push(head[n++]);
}
if(j!=b&&!use[i][b])
{
str="FILL(2)";
use[i][b]=1;
head[n]=new Node(i,b,v+1,n,m,str);
q.push(head[n++]);
}
//清空水
if(i&&!use[0][j])
{
use[0][j]=1;
str="DROP(1)";
head[n]=new Node(0,j,v+1,n,m,str);
q.push(head[n++]);
}
if(j&&!use[i][0])
{
use[i][0]=1;
str="DROP(2)";
head[n]=new Node(i,0,v+1,n,m,str);
q.push(head[n++]);
}
//倒水
if(i)
{
if(b-j>=i)
{
if(!use[0][i+j])
{
use[0][i+j]=1;
str="POUR(1,2)";
head[n]=new Node(0,i+j,v+1,n,m,str);
q.push(head[n]);
if(i+j==c)
{
s=v+1;
return n;
}
n++;
}
}
else if(!use[i-b+j][b])
{
use[i-b+j][b]=1;
str="POUR(1,2)";
head[n]=new Node(i-b+j,b,v+1,n,m,str);
q.push(head[n]);
if(i-b+j==c)
{
s=v+1;
return n;
}
n++;
}
}
if(j)
{
if(a-i>=j)
{
if(!use[i+j][0])
{
use[i+j][0]=1;
str="POUR(2,1)";
head[n]=new Node(i+j,0,v+1,n,m,str);
q.push(head[n]);
if(i+j==c)
{
s=v+1;
return n;
}
n++;
}
}
else if(!use[a][j-a+i])
{
use[a][j-a+i]=1;
str="POUR(2,1)";
head[n]=new Node(a,j-a+i,v+1,n,m,str);
q.push(head[n]);
if(j-a+i==c)
{
s=v+1;
return n;
}
n++;
}
}
}
return 0;
}
void print(int i)//回溯路径
{
if(head[i]==NULL) return;
print(head[i]->t);
cout<<head[i]->str<<endl;
}
int main()
{
int f;
while(cin>>a>>b>>c)
{
f=bfs();
if(f==0)
cout<<"impossible"<<endl;
else if(f==1)
{
cout<<f<<endl;
if(a==c)
cout<<"FILL(1)"<<endl;
else
cout<<"FILL(2)"<<endl;
}
else
{
cout<<s<<endl;
print(f);
}
}
return 0;
}
本文介绍了一个利用BFS算法解决两瓶不同容量的瓶子如何通过一系列操作达到装满特定容量水的问题。详细解释了算法实现过程,包括状态转移、边界条件判断和路径回溯。
748

被折叠的 条评论
为什么被折叠?



