zoukankan      html  css  js  c++  java
  • 【HDU 6171】Admiral(搜索+剪枝)

    多校10 1001 HDU 6171 Admiral

    题意

    目标状态是第i行有i+1个i数字(i=0~5)共6行。给你初始状态,数字0可以交换上一行最近的两个和下一行最近的两个。求20步以内到目标状态的最少步数是多少。

    题解

    设计一个估价函数来剪枝,每个数最少需要|a[i][j]-i|步回到自己的位置。当所有数回到自己位置,0自然也回到自己位置。所以估价函数不计算0。
    然后21个位置,每个位置数字是0~5,用三位2进制表示。总共63位2进制。long long可以记录状态。然后就是搜索了。

    代码

    #include <cstdio>
    #include <map>
    #include <cstdlib>
    #include <queue>
    using namespace std;
    #define mem(a,b) memset(a,b,sizeof(a))
    #define rep(i,l,r) for (int i=l;i<r;++i)
    typedef unsigned long long ull;
    int dx[4]={1,1,-1,-1},dy[4]={0,1,0,-1};
    map<ull,bool>vis;
    struct Sta{
    	int a[6][6],step,x,y;
    	Sta(){step=x=y=0;}
    };
    int gujia(Sta s){
    	int ans=0;
    	rep(i,0,6)rep(j,0,i+1)
    	if(s.a[i][j])ans+=abs(s.a[i][j]-i);
    	return ans;
    }
    ull haxi(Sta s){
    	ull ans=0;
    	rep(i,0,6)rep(j,0,i+1){
    		ans<<=3;ans|=s.a[i][j];
    	}
    	return ans;
    }
    int bfs(Sta s){
    	vis.clear();
    	queue<Sta>q;q.push(s);
    	while(!q.empty()){
    		Sta now=q.front();q.pop();
    		if(gujia(now)==0)return now.step;
    		rep(i,0,4){
    			int x=now.x,y=now.y;
    			int nx=x+dx[i],ny=y+dy[i];
    			if(nx>=0 && nx<6 && ny>=0 && ny<=nx){
    				swap(now.a[x][y],now.a[nx][ny]);
    				now.x=nx,now.y=ny,++now.step;
    				ull hx=haxi(now);
    				if(!vis[hx]&&gujia(now)+now.step<21){
    					q.push(now);
    					vis[hx]=true;
    				}
    				swap(now.a[x][y],now.a[nx][ny]);
    				now.x-=dx[i],now.y-=dy[i],--now.step;
    			}
    		}
    	}
    	return -1;
    }
    int main() {
    	int t;
    	scanf("%d",&t);
    	while(t--){
    		Sta s;
    		rep(i,0,6)
    		rep(j,0,i+1){
    			scanf("%d",&s.a[i][j]);
    			if(s.a[i][j]==0)s.x=i,s.y=j;
    		}
    		int ans=bfs(s);
    		if(ans==-1)puts("too difficult");else printf("%d
    ",ans);
    	}
    	return 0;
    }
    
  • 相关阅读:
    DDD 领域驱动设计-谈谈 Repository、IUnitOfWork 和 IDbContext 的实践
    UVA10071 Back to High School Physics
    UVA10071 Back to High School Physics
    UVA10055 Hashmat the Brave Warrior
    UVA10055 Hashmat the Brave Warrior
    UVA458 The Decoder
    UVA458 The Decoder
    HDU2054 A == B ?
    HDU2054 A == B ?
    POJ3414 Pots
  • 原文地址:https://www.cnblogs.com/flipped/p/7429644.html
Copyright © 2011-2022 走看看