HDU 1495非常可乐(BFS)使用数组简化代码
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1495
题目大意:三个容器相互倒水,直到将原有的液体平分,求最小次数
思路:bfs搜索六个方向(s->n ;s->m ; n->s ; n->m ;m->s ;m->n)
ac代码如下:
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <queue>
using namespace std;
struct re//定义结构体,名字为re
{
int a,b,c;
int step;
re(){};
re(int a1,int b1,int c1,int step1):a(a1),b(b1),c(c1),step(step1){}
};
int s,n,m;
int base[6][2]={{0,1},{0,2},{1,0},{1,2},{2,1},{2,0}};//六个方向,0代表s,1代表n,2代表m
int ba[3];//记录s,n,m的容量 //(s->n ;s->m ; n->s ; n->m ;m->s ;m->n)
int bc[3];//记录当下的s,n,m所含的可乐体积
int check[110][110][110];//检查该状态是否已出现过,避免重复倒可乐
void pour(int &x,int &y,int xx,int yy)//倒可乐函数
{ //行参含义:倒出可乐容器内当前可乐体积
//得到可乐容器内当前可乐体积
//倒出可乐的容器
//得到可乐的容器
int tt=x+y;
if(tt>ba[yy])
{
x=tt-ba[yy];
y=ba[yy];
}
else
{
x=0;
y=tt;
}
}
void bfs(int ss,int nn,int mm)
{
queue<re> q;
q.push(re(ss,0,0,0));
check[ss][0][0]=1;
while(!q.empty())
{
re t=q.front();
q.pop();
if((t.a==s/2&&t.b==s/2)||(t.a==s/2&&t.c==s/2)||(t.b==s/2&&t.c==s/2))//得到答案条件
{
cout<<t.step<<endl;
return;
}
for(int i=0;i<6;i++)
{
bc[0]=t.a;bc[1]=t.b;bc[2]=t.c;//得到当前三容器内可乐体积
pour(bc[base[i][0]],bc[base[i][1]],base[i][0],base[i][1]);//倒可乐
if(!check[bc[0]][bc[1]][bc[2]])
{
check[bc[0]][bc[1]][bc[2]]=1;
q.push(re(bc[0],bc[1],bc[2],t.step+1));
}
}
}
cout<<"NO"<<endl;
return;
}
int main()
{
//freopen("in.txt","r",stdin);
while(cin>>s>>n>>m&&s&&n&&m)
{
ba[0]=s;ba[1]=n;ba[2]=m;//为容器体积赋值
memset(check,0,sizeof(check));//初始化check数组
if(s%2==0)//如果可平分,bfs搜索
{
bfs(s,n,m);
}
else
cout<<"NO"<<endl;
}
return 0;
}