POJ 3278 Catch that Cow BFS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.