搜索-BFS-poj3278
2016-08-22 17:33
211 查看
题意:
给定 两个坐标X ,Y
给定三个操作 1: 2*x
2: x-1;
3: x+1;
找到最少变换的步骤可以将X变为Y;
思路:
一开始以为是个思维题。但是写半天发现不是。时间1S,数据量不大,广搜过了!
搜索从一点到另外三点。通过给定的三种步骤。#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
int n,m;
bool go[200011];
int step[200011];
void bfs()
{ queue <int > a;
if(n==m)
printf("0\n");
a.push(n);
go
=true;
step
=0;
int temp;
while(!a.empty())
{
int tep=a.front();
a.pop();
for(int i=1;i<=3;i++)
{
if(i==1)
{
temp=tep*2;
}
else if(i==2)
{
temp=tep-1;
}
else{
temp=tep+1;
}
if(temp<0||temp>100000)//注意这一步必须有,否则数字会无限大做下去。
continue;
if(go[temp]!=true)//这步骤优化可以保证所有都是在N个数字里循环
{
step[temp]=step[tep]+1;
a.push(temp);
if(temp==m)
{
printf("%d\n",step[temp]);
return ;
}
go[temp]=true;
}
}
}
}
int main()
{int flag=0;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(go,0,sizeof(go));
memset(step,0,sizeof(step));
bfs();
}
}
给定 两个坐标X ,Y
给定三个操作 1: 2*x
2: x-1;
3: x+1;
找到最少变换的步骤可以将X变为Y;
思路:
一开始以为是个思维题。但是写半天发现不是。时间1S,数据量不大,广搜过了!
搜索从一点到另外三点。通过给定的三种步骤。#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
int n,m;
bool go[200011];
int step[200011];
void bfs()
{ queue <int > a;
if(n==m)
printf("0\n");
a.push(n);
go
=true;
step
=0;
int temp;
while(!a.empty())
{
int tep=a.front();
a.pop();
for(int i=1;i<=3;i++)
{
if(i==1)
{
temp=tep*2;
}
else if(i==2)
{
temp=tep-1;
}
else{
temp=tep+1;
}
if(temp<0||temp>100000)//注意这一步必须有,否则数字会无限大做下去。
continue;
if(go[temp]!=true)//这步骤优化可以保证所有都是在N个数字里循环
{
step[temp]=step[tep]+1;
a.push(temp);
if(temp==m)
{
printf("%d\n",step[temp]);
return ;
}
go[temp]=true;
}
}
}
}
int main()
{int flag=0;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(go,0,sizeof(go));
memset(step,0,sizeof(step));
bfs();
}
}
相关文章推荐
- 广度优先搜索bfs与抓住那头奶牛(Catch that cow, poj3278)
- poj3278 线上的BFS搜索
- 【搜索BFS】poj3278--Catch That Cow(bfs)
- poj3278 Catch That Cow(bfs搜索)
- poj3278 Catch That Cow BFS搜索 TWT Tokyo Olympic 2combo-1
- poj3635 FULL tank(TLE) 有限制的最短路(BFS搜索)。
- hdu 4771 Stealing Harry Potter's Precious (2013亚洲区杭州现场赛)(搜索 bfs + dfs) 带权值的路径
- HDU 2579 (记忆化BFS搜索)
- 【BFS搜索】poj1945 Power Hungry Cows
- 图的广度优先查找(BFS: Breadth -First Search) (1)问题分析 BFS的策略是尽可能广泛地搜索图。它首先访问所有和初始顶点邻接的顶点,然后访问距离它两条边的所有未
- SDUT-3468 广度优先搜索练习之神奇的电梯(BFS)
- HDU 1195 Open the Lock 简单搜索-bfs
- [PKU 1077] 搜索之BFS & A*(上)
- 走迷宫--图的搜索(bfs)并记录路径
- hdu 1372 Knight Moves bfs搜索 解题报告
- HDU 1312 Red and Black 红与黑 搜索 dfs bfs
- 重学搜索yi.3:迷宫的最短路径--bfs
- 单向搜索bfs,PKU1077,八数码问题
- POJ 3626 Mud Puddles 练习 BFS 宽度优先搜索
- POJ 2251 Dungeon Master :NYOJ 353 3D dungeon (三维空间上的搜索 bfs )