N皇后加强版求助

P1219 [USACO1.5] 八皇后 Checker Challenge

Parrhesiates @ 2023-08-02 20:20:32

请问N皇后问题在N范围为10-14的时候怎么解决(不超过时间限制,我们校内的OJ)


by XuYueming @ 2023-08-02 20:27:15

使用二进制压缩,再用DFS可以解决。我的code:

#include <iostream>
#include <cstdio>
using namespace std;

int n;
int cnt=0;
int ALL;

inline int lowbit(int x){
    return x & -x;
}

void DFS(int now, int r, int c1, int c2){
    if (now == n+1){
        cnt++;
        return;
    }
    int put = ALL^(r | c1 | c2);
    for (int i=lowbit(put);put;put-=lowbit(put),i=lowbit(put)){
        DFS(now+1, r|i, ((c1|i) << 1)&ALL, (c2|i) >> 1);
    }
}

int main(){
    scanf("%d",&n);
    ALL = (1 << n) - 1;
    DFS(1, 0, 0, 0);
    printf("%d",cnt);
    return 0;
}

by XuYueming @ 2023-08-02 20:28:56

你甚至可以

#include <iostream>
#include <cstdio>
using namespace std;

int l[5] = { 724, 2680, 14200, 73712, 365596 };

int main() {
    cin >> n;
    cout << l[n - 10] << endl;
    return 0;
}

(没弄懂前别这样)


by NOI_AK_I @ 2023-08-02 21:34:48

你们的太难了吧

#include<stdio.h>
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
bool f[201][201];
int t,n,m,a[201],b[201],c[201],d[201],e[201];
int print()输出函数
{
    if(m<=2)
    {
        for(int i=1;i<=n;i++) cout<<e[i]<<" ";
    }
    if(m<=2) cout<<endl;
    m++;
}
void dfs(int k)深搜部分
{
    if(k==n+1) print();搜完了就输出
    for(int i=1;i<=n;i++)
    {
        if(!a[i]&&!c[i-k+n]&&!d[i+k])//判断能不能放
        {
            a[i]=1;这里标记为不能放
            c[i-k+n]=1;
            d[i+k]=1;
            e[k]=i;
            dfs(k+1);下一个皇后
            a[i]=0;回溯大法
            c[i-k+n]=0;
            d[i+k]=0;
        }
    }
}
int main()
{
     scanf("%d",&n);
     dfs(1);
     cout<<m;
}

by whatfuck @ 2023-08-03 15:28:47


by Parrhesiates @ 2023-08-03 16:17:00

@XuYueming 谢了


by Parrhesiates @ 2023-08-03 16:18:10

@whatfuck emm,虽然但是还是非常感谢你,辛苦了


by whatfuck @ 2023-08-06 20:42:53

我也是抄的,改了e下


by wangzih123 @ 2023-08-07 09:43:27

@whatfuck !?


by whatfuck @ 2023-08-07 11:11:53

咋啦,超了代码,一一试的,最后打表


by WSZZ666 @ 2023-08-16 13:54:30

orZ


| 下一页