poj3278Catch That Cow(bfs)
2015-12-14 20:03
387 查看
题目链接:
http://poj.org/problem?id=3278
题目大意就是给你人的位置和牛的位置,你每可以有三种方式移动
向左移动一步,或者向右移动一步,或者移动到你当前位置二倍的位置
问你移动多少次能到牛的地方。
一开始根本想不到用bfs,看来我还是too naive了=,=
AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
#define MAX 100005
int vis[MAX],n,k;
queue<int>q;
int step[MAX];
int head,next;
int bfs()
{
q.push(n);
step
=0;
vis
=1;
while(!q.empty())
{
head=q.front();
q.pop();
for(int i=0;i<3;i++)
{
if(i==0) next=head-1;
else if(i==1) next=head+1;
else next=head*2;
if(next>MAX || next<0) continue;
if(vis[next]==0)
{
q.push(next);
step[next]=step[head]+1;
vis[next]=1;
}
if(next==k) return step[next];
}
}
return -1;
}
int main()
{
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&k);
if(n>k)
printf("%d\n",n-k);
else{
printf("%d\n",bfs());
}
}
http://poj.org/problem?id=3278
题目大意就是给你人的位置和牛的位置,你每可以有三种方式移动
向左移动一步,或者向右移动一步,或者移动到你当前位置二倍的位置
问你移动多少次能到牛的地方。
一开始根本想不到用bfs,看来我还是too naive了=,=
AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
#define MAX 100005
int vis[MAX],n,k;
queue<int>q;
int step[MAX];
int head,next;
int bfs()
{
q.push(n);
step
=0;
vis
=1;
while(!q.empty())
{
head=q.front();
q.pop();
for(int i=0;i<3;i++)
{
if(i==0) next=head-1;
else if(i==1) next=head+1;
else next=head*2;
if(next>MAX || next<0) continue;
if(vis[next]==0)
{
q.push(next);
step[next]=step[head]+1;
vis[next]=1;
}
if(next==k) return step[next];
}
}
return -1;
}
int main()
{
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&k);
if(n>k)
printf("%d\n",n-k);
else{
printf("%d\n",bfs());
}
}
相关文章推荐
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1001
- POJ ACM 1002
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- POJ-2409-Let it Bead&&NYOJ-280-LK的项链
- POJ-1695-Magazine Delivery-dp
- POJ1523 SPF dfs
- POJ-1001 求高精度幂-大数乘法系列
- POJ-1003 Hangover
- POJ-1004 Financial Management
- 用单调栈解决最大连续矩形面积问题
- 2632 Crashing Robots的解决方法
- 1573 Robot Motion (简单题)
- POJ 1200 Crazy Search(简单哈希)
- Surrounded Regions
- Word Ladder, Gray Code
- 【高手回避】poj3268,一道很水的dijkstra算法题