hdu 1010 Tempter of the Bone

来源:互联网 发布:厦门楼市每日成交数据 编辑:程序博客网 时间:2024/04/29 10:55

题意就是询问小狗能不能走出迷宫,这个题目一看就知道一道dfs的题目了,一般的搜索算法都可以剪枝,可能一个小小的剪枝会提高你程序的效率很多倍


值得一提的是这个题有一个奇偶剪枝,我一开始也超时了,加进去马上就ac了


  4。剪枝方法:奇偶剪枝

                             把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 需要奇数步

                       从 0->0 需要偶数步
                       那么设所在位置 (x,y) 与 目标位置 (dx,dy)

                       如果abs(x-y)+abs(dx-dy)为偶数,则说明 abs(x-y) 和 abs(dx-dy)的奇偶性相同,需要走偶数步

                       如果abs(x-y)+abs(dx-dy)为奇数,那么说明 abs(x-y) 和 abs(dx-dy)的奇偶性不同,需要走奇数步

                       理解为 abs(si-sj)+abs(di-dj) 的奇偶性就确定了所需要的步数的奇偶性!!

                       而 (ti-setp)表示剩下还需要走的步数,由于题目要求要在 ti时 恰好到达,那么  (ti-step) 与 abs(x-y)+abs(dx-dy) 的奇偶性必须相同

                       因此 temp=ti-step-abs(dx-x)-abs(dy-y) 必然为偶数!



#include <iostream>#include <stdio.h>#include <cstring>#include <cmath>using namespace std;char map[10][10];bool ask[10][10];int startx,starty,endx,endy;int n,m,t;int fangxiang[4][2]={{0,1},{1,0},{0,-1},{-1,0}    };bool ok(int x,int y){    if (x<n && x>=0 && y<=m && y>=0 && ask[x][y]==0 && (map[x][y]=='.' || map[x][y]=='D' || map[x][y]=='S'))        return true;    return false;}bool dfs(int x,int y,int tmpt){    int temp;    temp=t-tmpt-abs(endx-x)-abs(endy-y);//剪枝    if (temp<0||temp%2==1) return false;        ask[x][y]=1;    if (map[x][y]=='D' && tmpt==t)        return true;    if (tmpt>t)        return false;    int xx,yy;        for (int i=0; i<4; ++i)    {        xx=x+fangxiang[i][0];        yy=y+fangxiang[i][1];                if (ok(xx,yy))        {            if (dfs(xx,yy,tmpt+1))                return true;        }                }    ask[x][y]=0;    return false;    }int main(){    while (cin>>n>>m>>t && (n||m||t))    {                for (int i=0; i<n; ++i)            for (int j=0; j<m; ++j)            {                cin>>map[i][j];                if (map[i][j]=='S')                {                    startx=i;                    starty=j;                }                if (map[i][j]=='D')                {                    endx=i;                    endy=j;                }                                    }                    if (fabs((double)(endx-startx))+fabs((double)(endy-starty))>t)//剪枝        {            cout<<"NO\n";            continue;        }            memset(ask,0,sizeof(ask));                if (dfs(startx,starty,0))            cout<<"YES\n";        else            cout<<"NO\n";                    }}