[HDU] [2717] Catch That Cow

Problem Description

Loading...

Problem Analysis

BFS is used here
that is, each time
check m+1, m-1, m*2
and whenever a point not yet visited is encountered, push it into the search queue
until the target point has a recorded distance

Note that bounds checks must be added to the search
to prevent array out-of-range and similar issues

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int n,e;
int MAX=100200;
int dis[100200];
void bfs(int m) {
	queue<int>q;
	q.push(m);
	while(q.front()!=e) {
		int t=q.front();
		if(t+1<MAX&&!dis[t+1]) {
			dis[t+1]=dis[t]+1;
			q.push(t+1);
		}
		if(t-1>=0&&!dis[t-1]) {
			dis[t-1]=dis[t]+1;
			q.push(t-1);
		}
		if(t*2<MAX&&!dis[t*2]) {
			dis[t*2]=dis[t]+1;
			q.push(t*2);
		}
		if(dis[e])
			break;
		q.pop();
	}
	return ;
}
int main() {
	while(scanf("%d %d",&n,&e)!=EOF) {
		memset(dis,0,sizeof(dis));
		bfs(n);
		printf("%d\n",dis[e]);
	}
	return 0;
}

Problem link: 【杭电】[2717]Catch That Cow

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...