http://acm.hdu.edu.cn/showproblem.php?pid=1010
题意:给出T,问第T秒是否能从S去到D
Sample Input
4 4 5
S.X.
..X.
..XD
....
3 4 5
S.X.
..X.
...D
0 0 0
Sample Output
NO
YES
这题有2个重要的剪枝要学习
剪枝前后对比
第一个是删掉奇偶剪枝后的情况
第二个是删掉步数剪枝后的情况
#include <iostream>
using namespace std;
char map[8][8];
int r, c, ttime, x2, y2; //ttime 是所给时间T,【r:行、c:列】
bool flag; //x2、y2是终点坐标
int x_move[4] = {0, 1, -1, 0};
int y_move[4] = {1, 0, 0, -1};
void dfs (int x, int y, int t) //t是走到当前坐标时的时刻
{
if (t > ttime) //超时
return ; //下面的tmp的意义:【剩余时间(ttime - t)(记为left)】与【从当前坐标走到终点所需时间( abs(x-x2) + abs(y-y2) )(记为win)】的差,如果tmp是奇数,说明left与win的奇偶性不同!也就是说在第T秒时,不可能从当前坐标走到终点!
int tmp = ttime - t - abs(x-x2) - abs(y-y2);
if (tmp < 0 || tmp & 1) //奇偶剪枝,非常重要,很抽象 Orz...
return ;
for (int i = 0; i < 4; i++)
{
int tx = x + x_move[i];
int ty = y + y_move[i];
if (tx < 0 || ty < 0 || tx >= r || ty >= c)
continue;
if (map[tx][ty] == 'D' && t + 1 == ttime)//到达终点且该时刻t+1为所给时间,即成功到达
{
flag = true;
return ;
}
if (map[tx][ty] == '.')
{
map[tx][ty] = 'X'; //已走格子变成墙,根据题意,已走格子不可再走
dfs (tx, ty, t+1);
if (flag) //成功
return ;
map[tx][ty] = '.'; //回溯
}
}
}
int main()
{
int i, j, x1, y1, empty;
while (scanf ("%d%d%d", &r, &c, &ttime) != EOF)
{
if (!r && !c && !ttime)
break;
empty = 0;
for (i = 0; i < r; i++)
{
scanf ("%s", map[i]);
for (j = 0; j < c; j++)
{
if (map[i][j] == 'S') //找到起点的坐标
x1 = i, y1 = j;
if (map[i][j] == 'D') //找到终点的坐标
x2 = i, y2 = j;
if (map[i][j] == '.') //计算总的可能行走的步数
empty++;
}
}
if (empty + 1 < ttime) //步数剪枝,常识,可行步数小于总时间,在T时刻肯定不可走到终点
{
puts ("NO");
continue;
}
flag = false;
dfs (x1, y1, 0);
if (flag)
puts ("YES");
else puts ("NO");
}
return 0;
}
- 大小: 23.3 KB
分享到:
相关推荐
HDU 1010-2500解题报告,ACMer可以借鉴一下
杭州电子科技大学oj平台上的第1010题,是关于搜索的题目,很不错的题
ACM比赛解题报告,包括hdu1880、zoj1010、zoj1015,为原创的报告,算法不一定最优的
The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105. Input Input...
The first line of the input contains an integer T(1≤T≤10), denoting the number of test cases. In each test case, there are two integers k,m(1≤k≤1018,1≤m≤100). Output For each test case, print ...
HDU的1250,主要是利用高精度加法,但是代码有点繁琐,效率不是很高
杭电ACMhdu1163
HDU1059的代码
hdu1001解题报告
hdu 1574 passed sorce
HDU的一题........HDU DP动态规
hdu acm 教案 搜索入门 hdu acm 教案 搜索入门
hdu2101AC代码
搜索 dfs 解题代码 hdu1241
hdu 5007 Post Robot 字符串枚举。 暴力一下就可以了。
hdu acm 教案 动态规划(1) hdu acm 教案 动态规划(1)
ACM HDU题目分类,我自己总结的大概只有十来个吧
hdu 1166线段树代码
HDU最全ac代码
hdu动态规划算法集锦