POJ Problem 3278 Catch That Cow
来源:互联网 发布:linux daemon fork 编辑:程序博客网 时间:2024/05/28 15:25
John在位置N处,奶牛在K处,John每次只能有以下两种移动方式:walking和teleporting
Walking:在一个单位时间里John可以从X处移动到X-1或X+1。
Teleporting:在一个单位时间里John可以从X处移动至2*X。
假设奶牛的位置不变,求John移动到奶牛所在位置所需的最短时间。
主要方法:用队列进行宽度优先搜索BFS,同时用一个数组标记已经访问过的点,减少算法时间。注意要考虑N >= K的情况,此时,N只能一直减一,直至等于K。
#include <iostream>#include <vector>#include <queue>#include <stdio.h>using namespace std;int main(){ int n, k; cin >> n >> k; int ans = 0; if(k <= n){ while(k != n){ n--; ans++; } cout << ans << endl; return 0; } queue<int> que; que.push(n); vector<int> arr(2*k+1, -1); arr[n] = 0; while(!que.empty()){ int s = que.size(); bool stop = false; while(s--){ int num = que.front(); que.pop(); if(num == k) { stop = true; break; } if(num+1 <= 2*k && arr[num+1] == -1){ que.push(num+1); arr[num+1] = ans; } if(num-1 >= 0 && num-1 <= 2*k && arr[num-1] == -1){ que.push(num-1); arr[num-1] = ans; } if(2*num <= 2*k && arr[2*num] == -1){ que.push(2*num); arr[2*num] = ans; } } if(stop) break; ans++; } printf("%d\n", ans); return 0;}
0 0
- POJ Problem 3278 Catch That Cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 catch that cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- Poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 Catch That Cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 - Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- java.net.URLEncode编码 与 URLDecode解码问题 %E5%9B%9B%E5%B7%9D
- DirectDraw_3
- 左边图片的文本框,当文字输入时改变图片,模仿微博登录框
- for,foreach,iterator的用法\区别\效率
- Android Studio运行提示Error:Execution failed for task ':app:buildInfoDebugLoader'
- POJ Problem 3278 Catch That Cow
- MyEclipse豆沙绿颜色设置
- CentOS6.5安装LAMP+Redis
- Linux中的EAGAIN含义
- 教你如何在Mac上搭建自己的服务器——Nginx
- Blockly概述
- 离线安装使用github
- iOS动态性(三) Method Swizzling以及AOP编程:在运行时进行代码注入
- SQLSERVER存储过程实例(下)