poj 3278 cow (bfs)
来源:互联网 发布:linux查看用户文件 编辑:程序博客网 时间:2024/06/14 13:18
写法一:模拟队列
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int N = 700500;
const int inf = 0x3f3f3f3f;
struct mark{
int x;
int k;
};
mark a[N];
int book[N];
int main()
{
int n, m;
while(scanf("%d %d", &n, &m)!=EOF)
{
if(n>m)
printf("%d\n", n-m);//加上这步可以大大优化,减少时间
else
{
int head = 0, tail=1;
a[0].x = n;
a[0].k = 0;
memset(book, 0 ,sizeof(book));
book[n] = 1;
while(head<tail)
{
if(a[head].x==m)
{
printf("%d", a[head].k);
break;
}
if(!book[a[head].x+1]&&a[head].x+1<=m)
{
a[tail].x = a[head].x+1;
book[a[head].x+1] = 1;
a[tail++].k=a[head].k+1;
}
if(!book[a[head].x-1]&&a[head].x-1>=0)
{
a[tail].x = a[head].x-1;
book[a[head].x-1] = 1;
a[tail++].k=a[head].k+1;
}
if(!book[a[head].x*2]&&a[head].x*2<=2*m)
{
a[tail].x = a[head].x*2;
book[a[head].x*2] = 1;
a[tail++].k=a[head].k+1;
}
head++;
}
}
}
return 0;
}
写法二:STL队列
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int N = 200500;
const int inf = 0x3f3f3f3f;
bool book[N];
int step[N];
int main()
{
int n, m;
while(scanf("%d %d", &n, &m)!=EOF)
{
if(n>m)
printf("%d\n", n-m);//stl必须得有这步。
else
{
memset(book, false ,sizeof(book));
memset(step, 0 ,sizeof(step));
int head, next, flag = 0;
queue<int>q;
q.push(n);
book[n] = true;
step[n] = 0;
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>=2*m||next<0)
continue;
if(!book[next])
{
q.push(next);
step[next] = step[head] + 1;
book[next] = 1;
}
if(next==m)
{
printf("%d\n", step[next]);
flag = 1;
break;
}
}
if(flag == 1)
break;
}
}
}
return 0;
}
- poj 3278 cow (bfs)
- poj 3278 Catch That Cow(bfs)
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow(BFS)
- POJ--3278:Catch That Cow (BFS)
- POJ 3278 - Catch That Cow(BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ - 3278 - Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ 3278-Catch That Cow(bfs)
- POJ-3278-Catch That Cow(BFS)
- POJ 3278Catch That Cow(BFS)
- POJ 3278 Catch That Cow(BFS)
- poj 3278 Catch That Cow(BFS)
- poj 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ.3278 Catch That Cow (BFS)
- C#与Arduino通过串口通信来控制LED灯的状态
- 韩信点兵
- 英尺到米的转换
- UVA 11520 Fill the Square .
- 关于win10系统下matlabR2014中mex -setup报错问题
- poj 3278 cow (bfs)
- 视频直播技术详解(8)直播云 SDK 性能测试模型
- 使用ioremap实现的简单驱动
- 线性回归
- 基于迅为4412精英版连接SIM7100C模块Android下调试——RIL库分析(二)
- Bootstrap-fileinput-master脚本正确却显示不出正确结果
- 摄氏度(C)与华氏(F)转换
- OpenJudge 8468 单词序列
- 路径中使用斜杠/和反斜杠\的区别