您的位置:首页 > 其它

POJ3278-Catch That Cow

2011-07-31 09:46 211 查看
转载请注明出处:優YoU http://user.qzone.qq.com/289065406/blog/1303558739


大致题意:

给定两个整数n和k

通过 n+1或n-1 或n*2 这3种操作,使得n==k

输出最少的操作次数



解题思路:

说实话,要不是人家把这题归类到BFS,我怎么也想不到用广搜的= = 自卑ing。。。



水题水题,三入口的BFS



注意的地方有二:

1、 由于用于广搜的 队列数组 和 标记数组 相当大,如果定义这两个数组时把它们扔到局部去,编译是可以的,但肯定执行不了,提交就等RE吧= =

大数组必须开为 全局 。。。常识常识。。。

2、 剪枝。直接广搜一样等着RE吧= =

不剪枝的同学试试输入n=0 k=100000。。。。。。铁定RE

怎么剪枝看我程序





//Memory Time 
//1292K   0MS 

#include<iostream>
using namespace std;

const int large=200030;

typedef class
{
	public:
		int x;
		int step;
}pos;

int n,k;
bool vist[large];   //数组较大,必须开为全局数组,不然肯定RE
pos queue[large];

void BFS(void)
{
	int head,tail;
	queue[head=tail=0].x=n;
	queue[tail++].step=0;

	vist
=true;

	while(head<tail)
	{
		pos w=queue[head++];

		if(w.x==k)
		{
			cout<<w.step<<endl;
			break;
		}

		if(w.x-1>=0 && !vist[w.x-1])     //w.x-1>=0  是剪枝
		{
			vist[w.x-1]=true;
			queue[tail].x=w.x-1;
			queue[tail++].step=w.step+1;
		}
		if(w.x<=k && !vist[w.x+1])     //w.x<=k  是剪枝
		{
			vist[w.x+1]=true;
			queue[tail].x=w.x+1;
			queue[tail++].step=w.step+1;
		}
		if(w.x<=k && !vist[2*w.x])     //w.x<=k  是剪枝
		{
			vist[2*w.x]=true;
			queue[tail].x=2*w.x;
			queue[tail++].step=w.step+1;
		}
	}

	return;
}

int main(void)
{
	while(cin>>n>>k)
	{
		memset(vist,false,sizeof(vist));
		BFS();
	}
	
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: