POJ 3278

来源:互联网 发布:java split有空字符串 编辑:程序博客网 时间:2024/05/21 17:07
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 40052 Accepted: 12475

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X - 1 orX + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N andK

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

Source

USACO 2007 Open Silver



大意是数N变成K的最少步数,一次变换可以是 n+1 n-1 n*2

周赛的时候做到的,看完题就把bfs敲好,提交MLE。。。好久没写搜索,都忘了标记。。太sb了。。


这是记录下代码吧

#include <cstdio>#include <vector>#include <algorithm>#include <cstring>#include <cmath>#include <string>#include <map>#include <queue>#include <set>using namespace std;#ifdef WINtypedef __int64 LL;#define iform "%I64d"#define oform "%I64d\n"#elsetypedef long long LL;#define iform "%lld"#define oform "%lld\n"#endif#define SI(a) scanf("%d", &(a))#define SDI(a, b) scanf("%d%d", &(a), &(b))#define S64I(a) scanf(iform, &(a))#define SS(a) scanf("%s", (a))#define SDS(a, b) scanf("%s%s", (a), (b))#define SC(a) scanf("%c", &(a))#define PI(a) printf("%d\n", (a))#define PS(a) puts(a)#define P64I(a) printf(oform, (a))#define Max(a, b) ((a) > (b) ? (a) : (b))#define Min(a, b) ((a) < (b) ? (a) : (b))#define MSET(a, b) (memset((a), (b), sizeof(a)))#define Mid(L, R) ((L) + ((R) - (L))/2)#define Abs(a) ((a) >= 0 ? (a) : -(a))#define REP(i, n) for(int (i)=0; (i) < (n); (i)++)#define FOR(i, a, n) for(int (i)=(a); (i) <= (n); (i)++)const int INF = 0x3f3f3f3f;const double eps = 10e-9;const int maxn = 100000 + 10;int n, k;const int di[2] = {1, -1};queue<int> Q;int step[maxn];int la[maxn];void bfs() {step[n] = 0;Q.push(n);la[n] = 0;while(!Q.empty()) {int cur = Q.front();Q.pop();if(cur == k) {return ;}for(int i=0; i<2; i++) {int newi = cur + di[i];if(newi >= 0 && newi <= 2*k && step[newi] == -1) {step[newi] = step[cur] + 1;Q.push(newi);la[newi] = cur;}}if(cur>0 && cur*2 <= 2*k && step[cur*2] == -1) {step[cur*2] = step[cur] + 1;Q.push(cur*2);la[cur*2] = cur;}}}int main() {SDI(n, k);if(n < k) {MSET(step, -1);bfs();PI(step[k]);//int ls = la[k];//while(ls) {//printf("%d ", ls);//ls = la[ls];//}} else {PI(n - k);}return 0;}






0 0
原创粉丝点击