FUZoj 2188:过河I【bfs】

本文介绍了一种使用广度优先搜索解决过河问题的方法。该问题要求将一定数量的羊和狼安全运送到河对岸,同时确保羊不被狼吃掉。通过构造状态空间并进行遍历,找到最少过河次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 过河I
Time Limit:3000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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

AC-code:

<span style="font-family:FangSong_GB2312;font-size:14px;"> #include<cstdio>
 #include<cstring>
 #include<queue>
 using namespace std;
 struct node
 {
 	int x,y,step,mark;
 }p,now;
 void bfs(int a,int b,int n)
 {
 	int i,j;
 	int vis[3][205][205];
 	memset(vis,0,sizeof(vis));
	now.x=a;
	now.y=b;
	now.step=0;
	now.mark=0; 
 	queue<node>q;
	q.push(now);
	vis[now.mark][now.x][now.y]=1;
	while(!q.empty())
	{
		p=q.front();
		if(p.x==a&&p.y==b&&p.mark==1)
		{
			printf("%d\n",p.step);
			return ;
		}
		q.pop();
		for(i=0;i<=p.y;i++)//狼 
		{
			for(j=0;j<=p.x;j++)//羊 
			{
				if(i+j==0)
					continue;
				if(j<i&&j)
					continue;
				if(i+j>n)
					continue; 
				now.x=a-p.x+j;
				now.y=b-p.y+i;
				now.step=p.step+1;
				now.mark=!p.mark;
				if((now.x<now.y&&now.x!=0)||(a-now.x<b-now.y&&a-now.x!=0))
					continue;
				if(!vis[now.mark][now.x][now.y])
				{
					vis[now.mark][now.x][now.y]=1;
					q.push(now);
				}
			}
		}
	}
	printf("-1\n");
 }
 int main()
 {
 	int x,y,n;
 	while(scanf("%d%d%d",&x,&y,&n)!=EOF)
		bfs(x,y,n);
	return 0;
  } </span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值