|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 柿子饼同学 于 2022-6-28 14:12 编辑
我的代码贴上, 主要 n = 13 的时候超时了 , 也不是很理解题解中的二进制优化 . 可以详细解释下嘛 , 谢谢
题目::https://www.luogu.com.cn/problem/P1219
题解::https://www.luogu.com.cn/problem/solution/P1219
- #include <bits/stdc++.h>
- using namespace std;
- int n, ans = 0, cnt = 1; // n个皇后, ans个解法
- int xys[15] = {0}; // 它的下标是 行 , 存储的值是 列
- bool check(int x, int y, int dep){ // 检查放的位置是否符合
- for(int i = 1; i < dep; i++){ // 同行列 , 对角线
- if(x == xys[i] || y == i || x+y == xys[i]+i || x-y == xys[i]-i) return 0;
- }
- return 1;
- }
- void print(){ // 输出
- for(int i = 1; i <= n; i++){
- cout << xys[i] << " ";
- }
- cout << endl;
- }
- void dfs(int dep){
- if(dep > n){
- if(ans <= 3) print(); // 输出前 3 组解法
- ans++; // 到头就走 , 总解法加一
- return;
- }
- else{
- for(int i = 1; i <= n; i++){
- if(check(i, dep, dep)){ // 符合条件就放
- xys[dep] = i;
- dfs(dep+1);
- xys[dep] = 0; // 回溯
- }
- }
- }
- }
- int main(){
- ios::sync_with_stdio(0);
- cin >> n;
- dfs(1);
- cout << ans << endl;
- return 0;
- }
复制代码
(话说 N 皇后只能用暴力算法嘛)
是这样吗?我也不知道对不对: - #include <iostream>
- using namespace std;
-
- int board[14];
- // 打印棋盘上皇后的位置
- int show(int N) {
- for(int i = 1; i <= N; i++) {
- cout << board[i] << " ";
- }
- cout << endl;
- return 0;
- }
- // 检查棋盘上的每个直线位置是否存在多个皇后
- bool check(int k) {
- for (int i = 1; i < k; ++i) {
- if ((board[i] == board[k]) or (board[i] - board[k] == k - i) or (board[i] - board[k] == i - k)) return false;
- }
- return true;
- }
- // 题解
- int solution(int N) {
- int k = 1, count = 0;
- board[k] = 1; // 从 (1, 1) 开始
- while(k > 0) {
- if(k <= N and board[k] <= N) {
- if(not check(k)) board[k]++;
- else {
- k++; // 往右移
- board[k] = 1; // 放置皇后
- }
- }
- else {
- if(k > N) {
- count++; // 计算解的总数
- if (count < 4) show(N); // 打印前三个解
- }
- k--;
- board[k]++;
- }
- }
- return count;
- }
-
- int main(void) {
- int N = 13;
- cout << solution(N);
- return 0;
- }
复制代码
|
|