Description
一个如下的 6×66×6 的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行、每列有且只有一个,每条对角线(包括两条主对角线的所有平行线)上至多有一个棋子。
上面的布局可以用序列 2 4 6 1 3 52 4 6 1 3 5 来描述,第 �i 个数字表示在第 �i 行的相应位置有一个棋子,如下:
行号 1 2 3 4 5 61 2 3 4 5 6
列号 2 4 6 1 3 52 4 6 1 3 5
这只是棋子放置的一个解。请编一个程序找出所有棋子放置的解。
并把它们以上面的序列方法输出,解按字典顺序排列。
请输出前 33 个解。最后一行是解的总个数。
Input
一行一个正整数 �n,表示棋盘是 �×�n×n 大小的。
Output
前三行为前三个解,每个解的两个数字之间用一个空格隔开。第四行只有一个数字,表示解的总数。
Sample 1
Inputcopy | Outputcopy |
---|---|
6 | 2 4 6 1 3 5 3 6 2 5 1 4 4 1 5 2 6 3 4 |
Hint
【数据范围】
对于 100%100% 的数据,6≤�≤136≤n≤13。
题目翻译来自NOCOW。
USACO Training Section 1.5
#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<map>
#define endl '\n'
#define ll long long
#define int ll
using namespace std;
const int N=1e6+7;
const int M=2e3+7;
int t,n,m;
int mp[M][M];
bool col[N]; //记录棋子的列位置
int sum=0;
bool check(int x,int y)
{
int x1=x,y1=y;
while(x1<=n&&y1<=n)
{
if(mp[x1][y1]) return 0;
x1++;
y1++;
}
x1=x,y1=y;
while(x1>=1&&y1>=1)
{
if(mp[x1][y1]) return 0;
x1--;
y1--;
}
x1 = x, y1 = y;
while (x1 >= 1 && y1 <= n) {
if (mp[x1][y1]) return 0;
x1--;
y1++;
}
x1 = x, y1 = y;
while (x1 <= n && y1 >= 1) {
if (mp[x1][y1]) return 0;
x1++;
y1--;
}
return 1;
}
void pt()
{
vector<int> ans;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(mp[i][j])
{
ans.push_back(j);
break;
}
}
}
for(auto &it:ans) cout<<it<<' ';
cout<<endl;
}
void dfs(int x)
{
if(x==n+1)
{
sum++;
if(sum<=3)
{
pt();
}
}
for(int i=1;i<=n;i++) //遍历列
{
if(col[i]||!check(x,i)) continue;
col[i]=1;
mp[x][i]=1;
dfs(x+1);
col[i]=0;
mp[x][i]=0;
}
}
signed main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
dfs(1);
cout<<sum<<endl;
return 0;
}