题解:AT_abc361_d [ABC361D] Go Stone Puzzle

· · 题解

2 ≤ N ≤ 14

看到这个就会想到搜索或状压。

这里用的是广搜。

注释放在代码里。

#include <bits/stdc++.h>
using namespace std;
#define int long long
struct Node{
    int sum,emp;
};
//特殊癖好:数组喜欢1006,而不是1005 
queue<Node> q;
int n,p,t,dis[(1<<17)+6][16];
//dis[i][j]:   为i的状态 第j、j+1个位置是空的
char c;
void bfs(){
    q.push({p,n+1});
    dis[p][n+1] = 1;
    //这里为了方便,不把它设为零
    //输出的时候 答案会-1
    while(!q.empty()){
        int sum = q.front().sum,emp = q.front().emp;
        //sum 压缩后的状态  emp 哪两个位置是空的 
        q.pop();
        int p = (1 << (n+1)),GG = (1 << (n+2-emp)); 
        for(int i = 1;i <= n+1; i++,p >>= 1){
            if(i == emp-1||i == emp||i == emp+1) continue;
            //如果选的位置有空的 跳过 
            int sumx = sum;
            if(sum&p){
                //如果这个位置为1 
                sumx -= p;
                //将这个位置归零 
                sumx |= GG;
                //移到 emp 
            }
            if(sum&(p>>1)){
                //与上面同理 
                sumx -= (p>>1);
                sumx |= (GG>>1);
            }
            if(!dis[sumx][i]){
                //根据广搜是一层一层搜的性质 只需要判断有没有遍历过即可 
                dis[sumx][i] = dis[sum][emp]+1;
                q.push({sumx,i});
            }
        }
    }
}
main(){
    cin >> n;
    //p q 将状态压缩后的二进制数
    //0 黑 1 白 
    for(int i = 1;i <= n; i++){
        cin >> c;
        p <<= 1;
        if(c == 'W') p++;
    }
    for(int i = 1;i <= n; i++){
        cin >> c;
        t <<= 1;
        if(c == 'W') t++;
    }
    p <<= 2;
    t <<= 2;
    //最后的n+1和n+2的位置是空的 
    bfs();
    if(dis[t][n+1]) cout << dis[t][n+1]-1;
    else cout << -1;
    return 0;
}