(双向bfs)hdu1401 Solitaire

传送门:hdu1401 Solitaire

第一个双向bfs题目,先粘个大佬的代码学习学习:

代码:

#include<bits/stdc++.h>
#define N 100005
#define P pair<int,int>
using namespace std;
typedef long long ll;
const int M=1e9+7;
const int inf=1e9+7;
struct node{
    int x[4],y[4],d,f;
    void sort()
    {
        for(int i=0;i<4;i++){
            for(int j=i+1;j<4;j++){
                if(x[i]>x[j]||(x[i]==x[j]&&y[i]>y[j])){
                    swap(x[i],x[j]);
                    swap(y[i],y[j]);
                }
            }
        }
    }
};
map<int,bool>mp[2];
int u[]={0,0,1,-1};
int v[]={1,-1,0,0};
bool juege(int x,int y){
    if(x<1||y<1||x>8||y>8)return 1;
    return 0;
}
int gethash(node p){
    int k=0;
    p.sort();
    for(int i=0;i<4;i++){
        k*=64;
        k+=p.x[i]*8+p.y[i]-9;
    }
    return k;
}
bool bfs(node s,node to)
{
    mp[s.f][gethash(s)]=1;
    mp[to.f][gethash(to)]=1;
    queue<node>Q;
    Q.push(s);Q.push(to);
    int ji[9][9];
    memset(ji,0,sizeof(ji));
    while(!Q.empty())
    {
        node p=Q.front();
        Q.pop();
        if(mp[!p.f][gethash(p)])return 1;
        for(int i=0;i<4;i++)
            ji[p.x[i]][p.y[i]]=1;
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<4;j++)
            {
                int x=p.x[i]+u[j],y=p.y[i]+v[j];
                if(juege(x,y))continue;
                if(ji[x][y]){
                    x+=u[j];
                    y+=v[j];
                    if(juege(x,y)||ji[x][y])continue;
                }
                node now=p;
                now.d++;
                now.x[i]=x;
                now.y[i]=y;
                int k=gethash(now);
                if(mp[p.f][k])continue;
                if(mp[!p.f][k])return 1;
                mp[p.f][k]=1;
                if(now.d<4)Q.push(now);
            }
        }
        for(int i=0;i<4;i++)
            ji[p.x[i]][p.y[i]]=0;
    }
    return 0;
}
int main()
{
    node s,to;
    while(~scanf("%d%d",&s.x[0],&s.y[0]))
    {
        mp[0].clear();
        mp[1].clear();
        for(int i=1;i<4;i++)
            scanf("%d%d",&s.x[i],&s.y[i]);
        for(int i=0;i<4;i++)
            scanf("%d%d",&to.x[i],&to.y[i]);
        s.d=0;s.f=1;
        to.d=0;to.f=0;
        if(bfs(s,to))printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37275680/article/details/81812570