基于随机化算法求解n后问题 c++代码
时间: 2023-06-20 17:04:18 浏览: 63
以下是基于随机化算法求解n后问题的C++代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MAXN = 100;
int n, ans[MAXN], cnt;
bool check(int x, int y) {
for (int i = 1; i < x; i++) {
if (ans[i] == y || abs(i - x) == abs(ans[i] - y)) {
return false;
}
}
return true;
}
void solve() {
srand((unsigned)time(NULL));
while (true) {
cnt++;
if (cnt > 1000000) {
cout << "No solution found!" << endl;
return;
}
for (int i = 1; i <= n; i++) {
ans[i] = rand() % n + 1;
}
bool flag = true;
for (int i = 1; i <= n; i++) {
if (!check(i, ans[i])) {
flag = false;
break;
}
}
if (flag) {
cout << "Solution found!" << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (j == ans[i]) {
cout << "Q ";
} else {
cout << ". ";
}
}
cout << endl;
}
return;
}
}
}
int main() {
cin >> n;
solve();
return 0;
}
```
代码中使用了随机化的思想,每次随机生成一个解,然后判断是否符合要求,如果符合则输出解,如果不符合则继续生成新的解,直到找到解或者尝试次数超过一定的限制。