黑白皇后 - 八皇后变种(标记查询)
作者:
WindSkyEnd
,
2025-04-08 17:45:02
· 山东
,
所有人可见
,
阅读 36
两重dfs最后一个数据点会TLE,耗时太多,这个方法先枚举了一遍得到了所有可以的结果,每次都保留了对应的列的信息位置,dfs结束后在结果中两两匹配,如果位置都没有重合,就符合要求,注意位置虽然不重合,但是黑白皇后可以互换,因此匹配成功一次结果加2
#include <bits/stdc++.h>
#define debug(x) cout<<"!"<<(x)<<"!"<<endl
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
int n;
const int N = 15 , M = 1e4;
int col[N] , dg[2*N] , udg[2*N];
int cnt ;
int res ;
int temp[N];
int total[M][N];
void dfs(int u){
if(u>=n){
for(int i = 0 ; i < n ; i++){
total[cnt][i] = temp[i];
}
cnt ++;
return ;
}
for(int i = 0 ; i < n ; i++){
if(!col[i] && !dg[u+i] && !udg[u-i+n]){
col[i] = dg[u+i] = udg[u-i+n] = true;
temp[u] = i;
dfs(u+1);
col[i] = dg[u+i] = udg[u-i+n] = false;
}
}
}
int main(){
cin >> n;
dfs(0);
for(int i = 0 ; i < cnt ; i++){
for(int j = i + 1 ; j < cnt ; j++){
bool flag = false;
for(int k = 0 ; k < n ; k++){
if(total[i][k]==total[j][k]){
flag = true;
break;
}
}
if(!flag) res += 2;
}
}
cout << res;
}