书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

奇偶剪枝

这个奇偶剪枝相当牛B呀,佩服。

HDU 1010 http://acm.hdu.edu.cn/showproblem.php?pid=1010

题目大意:就是让你来找一下,能否在限定的时间内从S到达D.

Sample Input:

4 4 5

S.X.

..X.

..XD

.... 

Sample Output:

NO 


View Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;

char Map[8][8];
int Used[8][8];
int Dir[4][2]={{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int H, W, T, Done;
int Sx, Sy, Ex, Ey;

int DFS(int h, int w, int Step)
{
int k;
if(Done==1) return 0;
if(Step==T)
{
if(h==Ex && w==Ey) Done=1;
return 0;
}

if(Step > T) return 0; //剪枝1

if(abs(Ex-h)+abs(Ey-w) > T-Step) return 0; //剪枝2

if((abs(Ex-h)+abs(Ey-w))%2 != (T-Step)%2) return 0; //剪枝3 这个就是奇偶性剪枝了,相当牛B

for(k=0; k<4; k++)
{
int tx = h+Dir[k][0];
int ty = w+Dir[k][1];
if(tx>=0 && tx<H && ty>=0 && ty<W && Used[tx][ty]==0 && Map[tx][ty]!='X')
{
Used[tx][ty] = 1;
DFS(tx, ty, Step+1);
Used[tx][ty] = 0;
}
}
}

int main()
{
int i, j;
while(cin>>H>>W>>T && (H+W+T))
{
for(i=0; i<H; i++)
for(j=0; j<W; j++)
{
cin>>Map[i][j];
if(Map[i][j]=='S')
{
Sx = i;
Sy = j;
}
if(Map[i][j]=='D')
{
Ex = i;
Ey = j;
}
}
Done = 0;
memset(Used, 0, sizeof(Used));
Used[Sx][Sy] = 1;
DFS(Sx, Sy, 0);
if(Done==1) cout<<"YES"<<endl;
else cout<<"NO"<<endl;

}
}



posted on 2012-03-27 23:33  More study needed.  阅读(205)  评论(0编辑  收藏  举报

导航

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!