zoukankan      html  css  js  c++  java
  • 【BZOJ1085】[SCOI2005]骑士精神 双向BFS

    【BZOJ1085】[SCOI2005]骑士精神

    Description

      在一个5×5的棋盘上有12个白色的骑士和12个黑色的骑士, 且有一个空位。在任何时候一个骑士都能按照骑士的走法(它可以走到和它横坐标相差为1,纵坐标相差为2或者横坐标相差为2,纵坐标相差为1的格子)移动到空位上。 给定一个初始的棋盘,怎样才能经过移动变成如下目标棋盘: 为了体现出骑士精神,他们必须以最少的步数完成任务。

    Input

      第一行有一个正整数T(T<=10),表示一共有N组数据。接下来有T个5×5的矩阵,0表示白色骑士,1表示黑色骑士,*表示空位。两组数据之间没有空行。

    Output

      对于每组数据都输出一行。如果能在15步以内(包括15步)到达目标状态,则输出步数,否则输出-1。

    Sample Input

    2
    10110
    01*11
    10111
    01001
    00000
    01011
    110*1
    01110
    01010
    00100

    Sample Output

    7
    -1

    题解:由于只需要15步,所以正着搜8步,反着搜7步即可。

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <queue>
    #include <utility>
    #include <map>
    #define F first
    #define S second
    #define mp(A,B) make_pair(A,B)
    #define P(A,B) (1<<(A*5+B))
    using namespace std;
    typedef pair<int,int> pii;
    
    const int S=33000480;
    map<pii,int> s1,s2;
    queue<pii> q;
    int dx[]={1,2,2,1,-1,-2,-2,-1},dy[]={2,1,-1,-2,-2,-1,1,2};
    char rd()
    {
    	char gc=getchar();
    	while(gc!='1'&&gc!='0'&&gc!='*')	gc=getchar();
    	return gc;
    }
    void work1()
    {
    	s1[mp(S,12)]=0;
    	q.push(mp(S,12));
    	while(!q.empty())
    	{
    		pii u=q.front(),v;
    		q.pop();
    		if(s1[u]==8)	continue;
    		int i,x=u.S/5,y=u.S%5,tx,ty,a;
    		for(i=0;i<8;i++)
    		{
    			tx=x+dx[i],ty=y+dy[i];
    			if(tx>=5||tx<0||ty>=5||ty<0)	continue;
    			v.S=tx*5+ty,a=((u.F>>v.S)&1),v.F=u.F^(a<<v.S),v.F|=(a<<(x*5+y));
    			if(s1.find(v)==s1.end())	q.push(v),s1[v]=s1[u]+1;
    		}
    	}
    }
    void work2()
    {
    	pii tmp=mp(0,0);
    	for(int i=24;i>=0;i--)
    	{
    		char gc=rd();
    		if(gc=='1')	tmp.F|=(1<<i);
    		if(gc=='*')	tmp.S=i;
    	}
    	s2.clear(),s2[tmp]=0;
    	q.push(tmp);
    	int ans=20;
    	while(!q.empty())
    	{
    		pii u=q.front(),v;
    		q.pop();
    		if(s1.find(u)!=s1.end())	ans=min(ans,s1[u]+s2[u]);
    		if(s2[u]==7)	continue;
    		int i,x=u.S/5,y=u.S%5,tx,ty,a;
    		for(i=0;i<8;i++)
    		{
    			tx=x+dx[i],ty=y+dy[i];
    			if(tx>=5||tx<0||ty>=5||ty<0)	continue;
    			v.S=tx*5+ty,a=((u.F>>v.S)&1),v.F=u.F^(a<<v.S),v.F|=(a<<(x*5+y));
    			if(s2.find(v)==s2.end())	q.push(v),s2[v]=s2[u]+1;
    		}
    	}
    	if(ans==20)	printf("-1
    ");
    	else	printf("%d
    ",ans);
    }
    int main()
    {
    	work1();
    	int T;
    	scanf("%d",&T);
    	while(T--)	work2();
    	return 0;
    }
  • 相关阅读:
    【流量劫持】SSLStrip 终极版 —— location 瞒天过海
    【流量劫持】沉默中的狂怒 —— Cookie 大喷发
    【流量劫持】SSLStrip 的未来 —— HTTPS 前端劫持
    Web 前端攻防(2014版)
    流量劫持 —— 浮层登录框的隐患
    流量劫持能有多大危害?
    流量劫持是如何产生的?
    XSS 前端防火墙 —— 整装待发
    XSS 前端防火墙 —— 天衣无缝的防护
    XSS 前端防火墙 —— 无懈可击的钩子
  • 原文地址:https://www.cnblogs.com/CQzhangyu/p/7242911.html
Copyright © 2011-2022 走看看