【HDOJ 1010】Tempter of the Bone

来源:互联网 发布:淘宝客服议价话术 编辑:程序博客网 时间:2024/06/05 23:08

【HDOJ 1010】Tempter of the Bone

dfs
要注意剪枝 否则超时 也算温习了一下很久前学的奇偶剪枝
如下图:
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
横纵坐标之和同奇偶性的点怎么走都需要偶数步 不同的需要奇数步
同时 两个数a b a+b为偶则奇偶性相同 为奇则不同
当前坐标(x,y) 目标坐标(ex,ey) 行走时间t 则x+y+ex+ey+t为偶数则可达
即x+y+ex+ey为偶(两坐标差偶数步) 时t需为偶
x+y+ex+ey为奇(两坐标差奇数步) 时t需为奇

再加上其余一些剪枝即可 否则必超。。。

代码如下:

#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <queue>#include <cmath>#define INF 0x3f3f3f3fusing namespace std;char mp[11][11];int dirx[] = { 0, 0, 1,-1};int diry[] = { 1,-1, 0, 0};int m,n,ex,ey;bool Get(int ax,int ay,int bx,int by,int t){    if(!((ax+ay+bx+by+t)&1)) return true;    else return false;}bool in(int x,int y)  {return (x > 0 && x <= m && y > 0 && y <= n);}bool dfs(int x,int y,int t){    //printf("%d %d %d\n",x,y,t);    if(!Get(x,y,ex,ey,t)) return false;    int i,xx,yy;    if(x == ex && y == ey)    {        if(!t) return true;        return false;    }    if(!t) return false;    for(i = 0; i < 4; ++i)    {        xx = x + dirx[i];        yy = y + diry[i];        if(!in(xx,yy)) continue;        if(mp[xx][yy] != 'X' )        {            mp[xx][yy] = 'X';            if(dfs(xx,yy,t-1)) return true;            mp[xx][yy] = '.';        }    }    return false;}int main(){    //freopen("in.in","r",stdin);    //freopen("out.txt","w",stdout);    int i,j,k,sx,sy,t,f,x,y,w;    while(~scanf("%d %d %d",&m,&n,&t) && (m+n+t))    {        f =  w = 0;        for(i = 1; i <= m; ++i)            scanf("%s",mp[i]+1);        for(i = 1; i <= m; ++i)            for(j = 1; j <= n; ++j)            {                if(mp[i][j] == 'S')                {                    sx = i;                    sy = j;                }                else if(mp[i][j] == 'D')                {                    for(k = 0; k < 4; ++k)                    {                        x = i+dirx[k];                        y = j+diry[k];                        if(!in(x,y)) continue;                        if(mp[x][y] == '.') f = 1;                    }                    ex = i;                    ey = j;                }                else if(mp[i][j] != '.')w++;            }        mp[sx][sy] = 'X';        if(n*m-w <= t) puts("NO");        else if(f && Get(sx,sy,ex,ey,t))            printf("%s\n",dfs(sx,sy,t)? "YES": "NO");        else puts("NO");    }    return 0;}
0 0