Tanky WooRSS

HDOJ 1010 Tempter of the Bone

19 Sep 2010
这篇博客是从旧博客 WordPress 迁移过来,内容可能存在转换异常。

题目传送门: http://acm.hdu.edu.cn/showproblem.php?pid=1010

第一次写剪枝的题目。 这里用了几次剪枝。 先贴出代码再说:

#include 
using namespace std;


char maze[8][8];
int dir[4][2] = \{\{0,-1}, {0,1}, {1,0}, {-1,0\}\};
int N, M, T;
int stax, stay, endx, endy;
int steps;
bool escape;
void DFS(int x, int y, int cnt)
{
    if(x>N || y>M || x<1 || y<1)        //剪枝3
        return;
    if(cnt==T && x==endx && y==endy)
        escape = 1;
    if(escape == 1)
        return;
    int temp = (T-cnt) - abs(x-endx) - abs(y-endy);
    if(temp<0 || temp&1)    //剪枝2
        return;
    for(int i=0; i<4; ++i)
    {
        if(maze[x+dir[i][0]][y+dir[i][1]] != 'X')
        {
            maze[x+dir[i][0]][y+dir[i][1]] = 'X';
            DFS(x+dir[i][0], y+dir[i][1], cnt+1);
            maze[x+dir[i][0]][y+dir[i][1]] = '.';
        }
    }
    return;
}

int main()
{
    //freopen("input.txt", "r", stdin);
    while(scanf("%d %d %d", &N;, &M;, &T;) && (N+M+T))
    {
        getchar();
        //printf("%d %d %d\n", N, M, T);
        escape = 0;
        steps = 0;
        stax = stay = endx = endy = 0;
        for(int i=1; i<=N; ++i)
        {
            for(int j=1; j<=M; ++j)
            {
                scanf("%c", &maze;[i][j]);
                //printf("%c", maze[i][j]);
                if(maze[i][j] == 'S')
                {
                    stax = i;
                    stay = j;
                }
                if(maze[i][j] == 'D')
                {
                    endx = i;
                    endy = j;
                }
                if(maze[i][j] == 'X')
                    steps++;
            }
            getchar();
            //printf("\n");
        }
        if(T >= M*N - steps)   //剪枝1
        {
            printf("NO\n");
            continue;
        }
        maze[stax][stay] = 'X';
        DFS(stax, stay, 0);
        if(escape == 1)
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

剪枝一: 对于可以走的最多步数比开门还要小,当然要剪掉。

剪枝二: 奇偶剪枝: 可以把map看成这样: 0 1 0 1 0 1 1 0 1 0 1 0 0 1 0 1 0 1 1 0 1 0 1 0 0 1 0 1 0 1 从为 0 的格子走一步,必然走向为 1 的格子 从为 1 的格子走一步,必然走向为 0 的格子 即: 0 ->1或1->0 必然是奇数步 0->0 走1->1 必然是偶数步 结论: 所以当遇到从 0 走向 0 但是要求时间是奇数的,或者, 从 1 走向 0 但是要求时间是偶数的 都可以直接判断不可达!

剪枝三: 边界条件。

剪枝无处不在,请看剪枝相关资料: 传送门:http://www.wutianqi.com/?p=1341