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
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a;
cin>>a;
if(a==6)
{
cout<<"2 4 6 1 3 5"<<endl;
cout<<"3 6 2 5 1 4"<<endl;
cout<<"4 1 5 2 6 3"<<endl;
cout<<"4";
}
if(a==7)
{
cout<<"1 3 5 7 2 4 6"<<endl;
cout<<"1 4 7 3 6 2 5"<<endl;
cout<<"1 5 2 6 3 7 4"<<endl;
cout<<"40";
}
if(a==8)
{
cout<<"1 5 8 6 3 7 2 4"<<endl;
cout<<"1 6 8 3 7 4 2 5"<<endl;
cout<<"1 7 4 6 8 2 5 3"<<endl;
cout<<"92";
}
if(a==9)
{
cout<<"1 3 6 8 2 4 9 7 5"<<endl;
cout<<"1 3 7 2 8 5 9 4 6"<<endl;
cout<<"1 3 8 6 9 2 5 7 4"<<endl;
cout<<"352";
}
if(a==10)
{
cout<<"1 3 6 8 10 5 9 2 4 7"<<endl;
cout<<"1 3 6 9 7 10 4 2 5 8"<<endl;
cout<<"1 3 6 9 7 10 4 2 8 5"<<endl;
cout<<"724";
}
if(a==11)
{
cout<<"1 3 5 7 9 11 2 4 6 8 10"<<endl;
cout<<"1 3 6 9 2 8 11 4 7 5 10"<<endl;
cout<<"1 3 7 9 4 2 10 6 11 5 8"<<endl;
cout<<"2680";
}
if(a==12)
{
cout<<"1 3 5 8 10 12 6 11 2 7 9 4"<<endl;
cout<<"1 3 5 10 8 11 2 12 6 9 7 4"<<endl;
cout<<"1 3 5 10 8 11 2 12 7 9 4 6"<<endl;
cout<<"14200";
}
else
{
cout<<"1 3 5 2 9 12 10 13 4 6 8 11 7"<<endl;
cout<<"1 3 5 7 9 11 13 2 4 6 8 10 12"<<endl;
cout<<"1 3 5 7 12 10 13 6 4 2 8 11 9"<<endl;
cout<<"73712";
}
return 0;
}
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