Problem 2188 过河I
Accept: 103 Submit: 258
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
Source
FOJ有奖月赛-2015年03月
实际上还是很简单的,想到BFS应该就过了,脑残的优先队列用错,wa了,还不如不用
ac代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<queue>
using namespace std;
int x,y,n;
int vis[220][220][2];
struct s
{
int x,y,flag;
int step;
friend bool operator < (s a ,s b)
{
return a.step>b.step;
}
}a,temp;
int bfs()
{
a.x=x;
a.y=y;
a.step=0;
a.flag=0;
priority_queue<struct s>q;
memset(vis,0,sizeof(vis));
vis[x][y][0]=1;
q.push(a);
int i,j;
while(!q.empty())
{
a=q.top();
q.pop();
//printf("%d %d %d\n",a.x,a.y,a.flag);
if(a.x==0&&a.y==0&&a.flag==1)
return a.step;
if(a.flag==0)
{
for(i=1;i<=a.y&&i<=n;i++)
{
int tx=a.x;
int ty=a.y-i;
if((tx>=ty||tx==0)&&(x-tx>=y-ty||(x-tx==0)))
{
if(vis[tx][ty][1])
continue;
temp.x=tx;
temp.y=ty;
temp.step=a.step+1;
temp.flag=1;
q.push(temp);
vis[tx][ty][1]=1;
}
}
for(i=1;i<=a.x;i++)
{
for(j=0;j<=i&&j<=a.y&&i+j<=n;j++)
{
int tx=a.x-i;
int ty=a.y-j;
if((tx>=ty||tx==0)&&(x-tx>=y-ty||(x-tx==0)))
{
if(vis[tx][ty][1])
continue;
temp.x=tx;
temp.y=ty;
temp.step=a.step+1;
temp.flag=1;
q.push(temp);
vis[tx][ty][1]=1;
}
}
}
}
else
{
for(i=1;i<=y-a.y&&i<=n;i++)
{
int tx=a.x;
int ty=a.y+i;
if((tx>=ty||tx==0)&&(x-tx>=y-ty||(x-tx==0)))
{
if(vis[tx][ty][0])
continue;
temp.x=tx;
temp.y=ty;
temp.step=a.step+1;
temp.flag=0;
q.push(temp);
vis[tx][ty][0]=1;
}
}
for(i=1;i<=x-a.x;i++)
{
for(j=0;j<=i&&j+i<=n&&j<=y-a.y;j++)
{
int tx=a.x+i;
int ty=a.y+j;
if((tx>=ty||tx==0)&&(x-tx>=y-ty||(x-tx==0)))
{
if(vis[tx][ty][0])
continue;
temp.x=tx;
temp.y=ty;
temp.step=a.step+1;
temp.flag=0;
q.push(temp);
vis[tx][ty][0]=1;
}
}
}
}
}
return -1;
}
int main()
{
//int x,y,n;
while(scanf("%d%d%d",&x,&y,&n)!=EOF)
{
int ans=bfs();
printf("%d\n",ans);
}
}