zoukankan      html  css  js  c++  java
  • HDU 1010 经典深搜+奇偶剪枝

    刚学搜索,不知道剪枝的重要性。

    超时代码:

    #include<iostream>
    #include<cstring>
    #include<cmath>
    using namespace std;
    char maps[10][10];
    const int moves[4][2] = {{0,-1},{0,1},{1,0},{-1,0}};
    
    int m,n,t,di,dj;
    bool escape;
    
    void DFS(int si,int sj,int cnt)
    {
    	if(si>n||si<=0||sj>m||sj<=0) return;
    	if(cnt==t&&si==di&&sj==dj)
    	{
    		escape = 1;
    		return;	
    	} 
    	for(int i=0;i<4;i++)
    	{
    		if(maps[si+moves[i][0]][sj+moves[i][1]]!='X')
    		{
    			maps[si+moves[i][0]][sj+moves[i][1]] = 'X';
    			DFS(si+moves[i][0],sj+moves[i][1],cnt+1);
    			maps[si+moves[i][0]][sj+moves[i][1]] = '.';
    		}
    	}
    	return;
    }
    
    int main()
    {
    	freopen("E:\\ACM\\HDOJ\\hdoj_1010\\in.txt","r",stdin);
    	int si,sj;
    	while(cin>>n>>m>>t)
    	{
    		if(n==0&&m==0&&t==0) break;
    		for(int i=1;i<=n;i++)
    		{
    			for(int j=1;j<=m;j++)
    			{
    				cin>>maps[i][j];
    				if(maps[i][j]=='S')
    				{
    					si = i;
    					sj = j;
    				}
    				else if(maps[i][j]=='D')
    				{
    					di = i;
    					dj = j;
    				}
    			}
    		}
    
    		escape = 0;
    		maps[si][sj] = 'X';
    		DFS(si,sj,0);
    		if(escape) cout<<"YES"<<endl;
    		else cout<<"NO"<<endl;
    	}
    	return 0;
    }



    网上搜下,是奇偶性剪枝:

    1. //Tempter of the Bone
    2.  
    3. /**//*//////////////////////////////////////////////////////////////////////////
    4.  
    5. 奇偶剪枝:把map看作
    6. 0 1 0 1 0 1
    7. 1 0 1 0 1 0
    8. 0 1 0 1 0 1
    9. 1 0 1 0 1 0
    10. 0 1 0 1 0 1
    11.  
    12. 从 0->1 需要奇数步
    13. 从 1->0 需要偶数步
    14. 那么设所在位置 (si,sj) 与 目标位置 (di,dj)
    15. 如果abs(si-sj)+abs(di-dj)为偶数,则说明 abs(si-sj) 和 abs(di-dj)的奇偶性相同,需要走偶数步
    16. 如果abs(si-sj)+abs(di-dj)为奇数,那么说明 abs(si-sj) 和 abs(di-dj)的奇偶性不同,需要走奇数步
    17. 理解为 abs(si-sj)+abs(di-dj) 的奇偶性就确定了所需要的步数的奇偶性!!
    18. 而 (t-cnt)表示剩下还需要走的步数,由于题目要求要在 t时 恰好到达,那么  (t-cnt) 与 abs(si-sj)+abs(di-dj) 的奇偶性必须相同
    19. 因此 temp=t-cnt-abs(sj-dj)-abs(si-di) 必然为偶数!


    /*奇偶剪枝的重要思想是:如果从当前位置还需要偶数(奇数)的时间才能到达目标位置,而当前剩余的时间数

    为奇数(偶数),那么即刻退出不再沿着纵深方向继续搜索。略微思考便知:奇偶剪枝的效果是立竿见影的!

    */ 

    1、temp = (t-cnt) - abs(si-di) - abs(sj-dj);

    if(temp<0||temp&1) return;

    2、可移动的步数大于给定的时间

    起到了立竿见影的效果!

  • 相关阅读:
    JSP所需要掌握的部分
    Parameter index out of range (1 > number of parameters, which is 0).
    Servlet到Servlet的请求转发与重定向的区别
    servlet范围:数据共享
    hihocoder 1169 猜数字
    UVA 1149 Bin Packing
    Using a Comparison Function for the Key Type
    STL Iterators
    SPOJ Pouring Water
    求DAG上两点的最短距离
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5835335.html
Copyright © 2011-2022 走看看