Title Link: http://poj.org/problem?id=3278
Test instructions: one-dimensional space. Initial coordinate n. Goal K. Move the way n-1,n+1,2*n, and then want to know the minimum number of steps to the end,
Idea: The BFS can no longer water. At first I don't want to knock. Knock on the happy re. Then know the existence of "pruning". is to optimize it. If the current location is now>k. That's the only way now-1 can go. Well. If you do not prune, re data such as 0 100000.
The focus is on pruning.
The AC code is attached:
1#include <stdio.h>2#include <string.h>3#include <iostream>4#include <queue>5 using namespacestd;6 7 intN, K;8 intvis[400100];9 intstep[400100];Ten intque[400100]; One A intDfs () { -memset (Vis,0,sizeof(Vis)); -memset (step,0,sizeof(step)); the intHead =0, tail =0; - -que[tail++] =N; -Vis[n] =1; +Step[n] =0; - + while(Head <tail) { A intnow = que[head++]; at if(now = =k) { - returnStep[k]; - } - - if(Now-1>=0&&!vis[now-1]) { -que[tail++] = now-1; invis[now-1] =1; -step[now-1] = Step[now] +1; to } + if(now < K &&!vis[now+1]) { -que[tail++] = now+1; thevis[now+1] =1; *step[now+1] = Step[now] +1; $ }Panax Notoginseng if(now < K &&!vis[now*2]) { -que[tail++] = now*2; thevis[now*2] =1; +step[now*2] = Step[now] +1; A } the } + return-1; - } $ $ intMain () { - while(Cin >> N >>k) { - intAns =dfs (); thecout << ans <<Endl; - }Wuyi return 0; the}
View Code
POJ 3278 Catch that Cow BFS