萌新求助,简单的双向bfs都能写炸qwq
查看原帖
萌新求助,简单的双向bfs都能写炸qwq
312393
ADay楼主2020/6/20 00:02

RT,全输出-1

#include<bits/stdc++.h>
using namespace std;

#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
char buf[1<<21],*p1=buf,*p2=buf;

inline int read()
{
    int s=0,f=1;
    char ch=getchar();
    while(!isdigit(ch))
    {
        if(ch=='-')f=-1;
        ch=getchar();
    }
    while(isdigit(ch))
    {
        s=s*10+ch-48;
        ch=getchar();
    }
    return s*f;
}

void getstr(string &x)
{
    char ch=getchar();
    while(!isalnum(ch)&&ch!='*')
        ch=getchar();
    while(isalnum(ch)||ch=='*')
    {
        if(ch=='*')
            x+="2";
        else
            x+=ch;
        ch=getchar();
    }
}

string st,ed="1111101111002110000100000";
int dx[]={1,-1,0,0},dy[]={0,0,1,-1};

inline void bfs()
{
	//string存状态,bool是正向还是反向搜的
    map<pair<string,bool>,int>dis;
    queue <pair<string,bool> >q;
    q.push(make_pair(st,1));
    dis[make_pair(st,1)]=0;
    q.push(make_pair(ed,0));
    dis[make_pair(ed,0)]=0;
    while(!q.empty())
    {
        string t=q.front().first;
        bool flag=q.front().second;
        pair<string,bool>g=q.front();
        //cout<<t<<endl;
        if(dis[g]>8)
            break;
        q.pop();
        int p=t.find('2');
        int x=p/5,y=p%5;
        for(int i=0;i<4;i++)
        {
            int xx=x+dx[i],yy=y+dy[i];
            if(xx<0||xx>4||yy<0||yy>4)continue;
            int pp=xx*5+yy;
            string tt=t;
            pair<string,bool>gg=g;
            gg.first=tt;
            swap(tt[p],tt[pp]);
            if(dis[gg])continue;
            gg.second=!gg.second;
            if(dis[gg])
            {
                printf("%d\n",dis[gg]+dis[g]);
                return;
            }
            gg.second=!gg.second;
            q.push(gg);
            dis[gg]=dis[g]+1;
        }
    }
    puts("-1");
}

int main()
{

    int T=read();
    while(T--)
    {
        int i=5;
        st="";
        while(i--)getstr(st);
        bfs();
    }
    return 0;
}
2020/6/20 00:02
加载中...