想问下我这样写有没有优化的方法? 反正他要输出的是一群不等的数,我就遍历他的全排列,一个一个找,
显然要判断给定的一个排列满不满足条件,只要看行号减对应的列号所得的结果没有相同的(有相同的就不满足),行号加对应的列号没有相同的就可以了。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
#define NUM 20
using namespace std;
int a[NUM];
int main() {
int n, cnt = 0;
cin >> n;
for (int i = 0; i <= n; i++) {
a[i] = i; //获得初始的排列
}
do {
int t[NUM], s[NUM];
for (int i = 1; i <= n; i++) { //s[]存对应的行号加列号
s[i] = a[i] + i;
}
for (int i = 1; i <= n; i++) { //t[]存对应的列号减行号
t[i] = a[i] - i;
}
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (t[i] == t[j] || s[i] == s[j]) { //如果有相等的,则直接舍去
goto stop;
}
}
}
cnt++;
if (cnt > 3)goto stop;
for (int i = 1; i <= n; i++) { //如果没有,则输出对应的排列
cout << a[i];
if (i != n) {
cout << ' ';
}
}
cout << endl;
stop:;
} while (next_permutation(a + 1, a + n + 1)); //遍历全排列
cout << cnt;
}