POJ 3278 第一道BFS 100题 纪念一下

39 篇文章 0 订阅

题目在 http://poj.org/problem?id=3278

这个题目过的还是比较艰难的,主要是因为我没有一下子用最好的办法做,很多时候,还是没有完全区分开什么时候用BFS, 什么时候用DFS

再做几个题目慢慢总结吧,不过做了这个题目就有100道题目了,继续加油呀~ Fight For oFFers


Source Code

Problem: 3278 User: hopeztm
Memory: 2308K Time: 141MS
Language: C++ Result: Accepted
  • Source Code
    #include <stdio.h>
    #include <memory.h>
    #include <queue>
    using namespace std;
    #define MAX_NUM 200003
    #define MAX_INT 1000000000
    #define MIN(x, y, z) (x < y ? x : y) < z ? (x < y ? x : y) : z
    
    int num[MAX_NUM];
    int visit[MAX_NUM];
    int From, To;
    
    int GetMinSteps(int i, int target)
    {
    	queue<int> t;
    	t.push(i);
    	int current;
    	num[i] = 0;
    	visit[i] = true;
    	while(!t.empty())
    	{
    		current = t.front();
    		t.pop();
    
    		if(current == To)
    			break;
    		if( current - 1 >= 0 && !visit[current-1])
    		{
    			visit[current] = true;
    			num[current - 1] = min(num[current - 1], num[current] + 1);
    			t.push(current - 1);
    		}
    		if(current + 1 <= To && !visit[current + 1] )
    		{
    			visit[current + 1] = true;
    			num[current+1] = min(num[current + 1], num[current] + 1);
    			t.push(current + 1);
    		}
    		if(2 * current < 2 * To  && !visit[2 * current] )
    		{
    			visit[2 * current ] = true;
    			num[current * 2] = min(num[current * 2], num[current] + 1);
    			t.push(2 * current);
    		}
    	
    	}
    	return num[To];
    	
    }
    int main()
    {
    	while(scanf("%d%d", &From, &To) != EOF)
    	{
    		memset(visit, 0, sizeof(visit));  
    		memset(num, 0x7F, sizeof(num));
    
    		printf("%d\n", GetMinSteps(From, To));
    	}
    	return 0;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值