HDU 1495 非常可乐 BFS 搜索

时间:2022-04-08 17:07:54

http://acm.hdu.edu.cn/showproblem.php?pid=1495

题目就不说了, 说说思路!

倒可乐 无非有6种情况:

1. S 向 M 倒

2. S 向 N 倒

3. N 向 M 倒

4. N 向 S 倒

5. M 向 S 倒

6. M 向 N 倒

根据上述的六种情况来进行模拟, 每次模拟的结果都放进队列里面。

注意: 还要用到标记数组,防止数据重复进入队列导致爆栈。

 #include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<string.h>
#include<iostream>
using namespace std;
#define maxn 110 struct Node
{
int m;//M瓶子中装的可乐数m
int n;
int s;
int k;//总共倒的次数
};
int M, N, S;
int BFS(Node P);
bool vis[maxn][maxn][maxn];//标记此情况是否有过, 防止重复
int main()
{
Node P;
while(scanf("%d%d%d",&S,&M,&N),M+N+S)
{
int t;
if(M < N)//将M存为最大的
t = M, M = N, N = t;
memset(vis,,sizeof(vis));
P.s = S, P.m = P.n = P.k = ;
int ans = -;
if(S% == )//奇数是没法平分的
ans = BFS(P); if(ans == -)
printf("NO\n");
else
printf("%d\n",ans);
}
return ;
} int BFS(Node P)
{
queue<Node> Q;
Q.push(P);
int x;
while( !Q.empty() )
{
Node Pn;
Pn = Q.front();
Q.pop(); if(Pn.s == S/ && Pn.m == S/ )//当两个瓶子都是S/2则满足
return Pn.k; P.k = Pn.k + ;
/*下面就是倒可乐的过程*/
if(Pn.s < S)
{
x = S - Pn.s; if(Pn.n > x && !vis[S][Pn.n-x][Pn.m])
{
vis[S][Pn.n-x][Pn.m] = ;
P.s = S, P.m = Pn.m, P.n = Pn.n-x;
Q.push(P);
}
else if(Pn.n <= x && !vis[Pn.s+Pn.n][][Pn.m])
{
vis[Pn.s+Pn.n][][Pn.m] = ;
P.s = Pn.s + Pn.n, P.m = Pn.m, P.n = ;
Q.push(P);
} if(Pn.m > x && !vis[S][Pn.n][Pn.m-x])
{
vis[S][Pn.n][Pn.m-x] = ;
P.s = S, P.n = Pn.n, P.m = Pn.m-x;
Q.push(P);
}
else if(Pn.m <= x && !vis[Pn.s+Pn.m][Pn.n][])
{
vis[Pn.s+Pn.m][Pn.n][] = ;
P.s = Pn.s+Pn.m, P.n = Pn.n, P.m = ;
Q.push(P);
}
} if(Pn.n < N)
{
x = N - Pn.n; if(Pn.s > x && !vis[Pn.s-x][N][Pn.m])
{
vis[Pn.s-x][N][Pn.m] = ;
P.s = Pn.s-x, P.n = N, P.m = Pn.m;
Q.push(P);
}
else if(Pn.s <= x && !vis[][Pn.n+Pn.s][Pn.m])
{
vis[][Pn.n+Pn.s][Pn.m] = ;
P.s = , P.n = Pn.n+Pn.s, P.m = Pn.m;
Q.push(P);
} if(Pn.m > x && !vis[Pn.s][N][Pn.m-x])
{
vis[Pn.s][N][Pn.m-x] = ;
P.s = Pn.s, P.n = N, P.m = Pn.m-x;
Q.push(P);
}
else if(Pn.m <= x && !vis[Pn.s][Pn.n+Pn.m][])
{
vis[Pn.s][Pn.n+Pn.m][] = ;
P.s = Pn.s, P.n = Pn.n+Pn.m, P.m = ;
Q.push(P);
}
} if(Pn.m < M)
{
x = M - Pn.m; if(Pn.s > x && !vis[Pn.s-x][Pn.n][M])
{
vis[Pn.s-x][Pn.n][M] = ;
P.s = Pn.s-x, P.n = Pn.n, P.m = M;
Q.push(P);
}
else if(Pn.s <= x && !vis[][Pn.n][Pn.m+Pn.s])
{
vis[][Pn.n][Pn.m+Pn.s] = ;
P.s = , P.n = Pn.n, P.m = Pn.m+Pn.s;
Q.push(P);
} if(Pn.n > x && !vis[Pn.s][Pn.n-x][M])
{
vis[Pn.s][Pn.n-x][M] = ;
P.s = Pn.s, P.n = Pn.n-x, P.m = M;
Q.push(P);
}
else if(Pn.n <= x && !vis[Pn.s][][Pn.m+Pn.n])
{
vis[Pn.s][][Pn.m+Pn.n] = ;
P.s = Pn.s-x, P.n =, P.m = Pn.m+Pn.n;
Q.push(P);
}
}
}
return -;
}