您的位置:首页 > 其它

hdu 1495 非常可乐(BFS)

2018-01-21 09:44 477 查看
题意:三个杯子,一开始只有第一个杯子有水(满的)。判断是否能通过互相倒水,倒出平分的情况,输出最小步数,或者NO

题解:BFS6种倒水情况即可。详情看代码注释。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 101;
struct node{
int x;
int y;
int z;
int step;
};
queue<node> q;
int book[maxn][maxn][maxn]; // 标记数组
int a,b,c,aim;
int check(int x,int y,int z)//平分条件
{
if(x == 0 && y == z)
return 1;
if(y == 0 && x == z)
return 1;
if(z == 0 && x == y)
return 1;
return 0;
}
void bfs(){
node now,next;
now.step = 0;
now.x = a;
now.y = 0;
now.z = 0;
book[now.x][now.y][now.z] = 1;
q.push(now);
while(!q.empty()){
now = q.front();
q.pop();
if(check(now.x,now.y,now.z)){
//cout << now.x << now.y << now.z << endl;
cout << now.step << endl;
return ;
}
for(int i = 1 ; i <= 6 ; i ++){
if(i == 1){ // a >> b
int sum = now.x + now.y;
if(sum <= b){
next.y = sum;
next.x = 0;
}
else {
next.y = b;
next.x = sum - b;
}
next.z = now.z;
if(!book[next.x][next.y][next.z]){
book[next.x][next.y][next.z] = 1;
next.step = now.step + 1;
q.push(next);
}
}
if(i == 2){ // a >> c
int sum = now.x + now.z;
if(sum <= c){
next.z = sum;
next.x = 0;
}
else {
next.z = c;
next.x = sum - c;
}
next.y = now.y;
if(!book[next.x][next.y][next.z]){
book[next.x][next.y][next.z] = 1;
next.step = now.step + 1;
q.push(next);
}
}
if(i == 3){ // b >> a
int sum = now.x + now.y;
if(sum <= a){
next.y = 0;
next.x = sum;
}
else {
next.y = sum - a;
next.x = a;
}
next.z = now.z;
if(!book[next.x][next.y][next.z]){
book[next.x][next.y][next.z] = 1;
next.step = now.step + 1;
q.push(next);
}
}
if(i == 4){ // b >> c
int sum = now.z + now.y;
if(sum <= c){
next.y = 0;
next.z = sum;
}
else {
next.y = sum - c;
next.z = c;
}
next.x = now.x;
if(!book[next.x][next.y][next.z]){
book[next.x][next.y][next.z] = 1;
next.step = now.step + 1;
q.push(next);
}
}
if(i == 5){ // c >> a
int sum = now.x + now.z;
if(sum <= a){
next.z = 0;
next.x = sum;
}
else {
next.z = sum - a;
next.x = a;
}
next.y = now.y;
if(!book[next.x][next.y][next.z]){
book[next.x][next.y][next.z] = 1;
next.step = now.step + 1;
q.push(next);
}
}
if(i == 6){ // c >> b
int sum = now.z + now.y;
if(sum <= b){
next.y = sum;
next.z = 0;
}
else {
next.y = b;
next.z = sum - b;
}
next.x = now.x;
if(!book[next.x][next.y][next.z]){
book[next.x][next.y][next.z] = 1;
next.step = now.step + 1;
q.push(next);
}
}
}
}
cout << "NO" << endl;
}
int main(){
while(cin >> a >> b >> c){
if(a == 0 && b == 0 && c== 0) break;
memset(book,0,sizeof(book)); // 清空很重要
while(!q.empty())
q.pop();
if(a%2 == 1) { // 若为奇数肯定不可能平分
cout << "NO"<<endl;
continue;
}
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: