您的位置:首页 > 其它

fzoj Problem 2188 过河I 【BFS】

2015-12-09 17:04 381 查看
Problem 2188 过河I


Accept: 97    Submit: 246
Time Limit: 3000 mSec    Memory Limit : 32768 KB



Problem Description

一天,小明需要把x只羊和y只狼运输到河对面。船可以容纳n只动物和小明。每次小明划船时,都必须至少有一只动物来陪他,不然他会感到厌倦,不安。不论是船上还是岸上,狼的数量如果超过羊,狼就会把羊吃掉。小明需要把所有动物送到对面,且没有羊被吃掉,最少需要多少次他才可以穿过这条河?



Input

有多组数据,每组第一行输入3个整数想x, y, n (0≤ x, y,n ≤ 200)



Output

如果可以把所有动物都送过河,且没有羊死亡,则输出一个整数:最少的次数。否则输出 -1 .



Sample Input

3 3 233 33 3



Sample Output

11-1



Hint

第一个样例

次数 船 方向 左岸 右岸(狼 羊)

0: 0 0 3 3 0 0

1: 2 0 > 1 3 2 0

2: 1 0 < 2 3 1 0

3: 2 0 > 0 3 3 0

4: 1 0 < 1 3 2 0

5: 0 2 > 1 1 2 2

6: 1 1 < 2 2 1 1

7: 0 2 > 2 0 1 3

8: 1 0 < 3 0 0 3

9: 2 0 > 1 0 2 3

10: 1 0 < 2 0 1 3

11: 2 0 > 0 0 3 3

BFS模拟过河即可。和三个水杯差不多吧。

AC代码:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#define INF 0x3f3f3f
#define eps 1e-4
#define MAXN (200+10)
#define MAXM (100000)
#define Ri(a) scanf("%d", &a)
#define Rl(a) scanf("%lld", &a)
#define Rf(a) scanf("%lf", &a)
#define Rs(a) scanf("%s", a)
#define Pi(a) printf("%d\n", (a))
#define Pf(a) printf("%.2lf\n", (a))
#define Pl(a) printf("%lld\n", (a))
#define Ps(a) printf("%s\n", (a))
#define W(a) while(a--)
#define CLR(a, b) memset(a, (b), sizeof(a))
#define MOD 1000000007
#define LL long long
#define lson o<<1, l, mid
#define rson o<<1|1, mid+1, r
#define ll o<<1
#define rr o<<1|1
using namespace std;
struct Node{
int x, y, step, mark;
};
bool vis[2][MAXN][MAXN];
void BFS(int x, int y, int n)
{
queue<Node> Q;
Node now, next; CLR(vis, false);
now.x = x; now.y = y; now.mark = 0; now.step = 0; Q.push(now);
vis[now.mark][now.x][now.y] = true;
while(!Q.empty())
{
now = Q.front();
Q.pop();
if(now.mark == 1 && now.x == x && now.y == y)
{
printf("%d\n", now.step);
return ;
}
int dx = x - now.x, dy = y - now.y;
for(int i = 0; i <= now.x; i++)
{
for(int j = 0; j <= now.y; j++)
{
if(i + j > n || i + j == 0)
continue;
if(i && i < j) continue;
if((dx + i != 0 && dx + i < dy + j) || (now.x - i != 0 && now.x - i < now.y - j))
continue;
next.x = dx + i; next.y = dy + j;
next.step = now.step + 1;
next.mark = 1 - now.mark;
if(!vis[next.mark][next.x][next.y])
{
vis[next.mark][next.x][next.y] = true;
Q.push(next);
}
}
}
}
printf("-1\n");
}
int main()
{
int x, y, n;
while(scanf("%d%d%d", &x, &y, &n) != EOF){
BFS(x, y, n);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: