HDU 1010 Tempter of the Bone

本文探讨了一道搜索回溯题目,通过学习并应用剪枝技巧,显著提高了解题速度。重点介绍了奇偶剪枝策略及其在解决特定问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是一道搜索+回溯的题目。。依旧很坑爹……让我感受到人生无处不坑爹。


话说收获最大的是通过这道题学到了剪枝技巧,刚开始做完了是TLE的。然后上网搜索,学了“奇偶剪枝”,

剪枝后快了几千倍的速度。。真让人汗颜。


题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1010


附上额外测试数据:


2 2 3
D.
.S
正确输出是NO


注意  the doggie had to arrive at the door on exactly the T-th second  这一句。


AC代码如下:

#include <iostream>
#include <cmath>
using namespace std;

int m,n,bx,by,ex,ey,s,wall;
char map[7][7];
int dx[4]={ 0,0,-1,1 },
	 dy[4]={ -1,1,0,0 };
bool flag;
bool check(int x ,int y)
{
	if(x<0 || x>m-1 || y<0 || y>n-1 ) return false;
	if(map[x][y]=='X') return false;
	return true;
}

void dfs( int x,int y,int dep )
{
	if ( flag)  return ;
	if(x==ex && y==ey && dep==s ) flag=true;//
	int tx,ty;
	//=========这两行剪枝很关键===========
		int temp = (s-dep) - abs(x-ex) - abs(y-ey);
		if(temp<0 || temp%2==1)  return;
	//=========传说中的奇偶剪枝============
	for(int i=0;i<4;i++)
	{
		tx=x+dx[i];
		ty=y+dy[i];
		if( check(tx,ty)  )
		{
			map[tx][ty]='X';
			dfs(tx,ty,dep+1);
			map[tx][ty]='.';
		}
	}
}

int main()
{
	while(cin>>m>>n>>s,m || n || s)
	{
		wall=0;
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<n;j++)
			{
				cin>>map[i][j];
				if(map[i][j]=='S') {bx=i;by=j; map[i][j]='X'; }
				else if(map[i][j]=='D') {ex=i;ey=j; }
				else if(map[i][j]=='X') {wall++; }
			}
		}
		flag=false;
		if( m*n-wall>s ) dfs(bx,by,0);
		if(flag) cout<<"YES\n";
		else cout<<"NO\n";
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值