Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

水题~最基础的BFS

Posted by xiexinxinlove at 2014-08-06 09:06:24 on Problem 3278 and last updated at 2014-08-06 09:06:53
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int Max = 100000 + 10;
int vis[Max];
int t[Max]; //记录时间
int n,k; 

void bfs()
{
	int now,temp;
	queue<int> q;
	q.push(n);
	while(!q.empty())
	{
		now = q.front();
		q.pop();
		if(now == k)
		{
			cout<<t[now]<<endl;
			return;
		}
		
		for(int i=1; i<=3; i++)
		{
			if(i == 1)
			{
				temp = now + 1;
			}
			if(i == 2)
			{
				temp = now - 1;
			}
			if(i == 3)
			{
				temp = now * 2;
			}
			if(!vis[temp] && temp >= 0 && temp < Max)
			{
				vis[temp] = 1;
				t[temp] = t[now] + 1;
				q.push(temp);
			}
		}
	}
}
		
int main()
{
	while(scanf("%d %d",&n,&k) != EOF)
	{
		memset(vis, 0, sizeof(vis));
		bfs();
	}
	return 0;
}
		

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator