问题 D: 八皇后

旧街凉风 提交于 2020-02-15 23:55:41
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

const int N = 8;
vector<long> s;

bool flag[N] = {false};
int a[N];

void help(int index) {
    if (index == N + 1) {
        for (int j = 1; j <= N; ++j) {
            for (int i = j + 1; i <= N; ++i) {
                if (abs(i - j) == abs(a[i] - a[j])) return;
            }
        }

        long temp = 0;
        for (int i = 1; i <= N; ++i) {
            temp = temp * 10 + a[i];
        }
        s.push_back(temp);
    }
    for (int i = 1; i <= N; ++i) {
        if (!flag[i]) {
            flag[i] = true;
            a[index] = i;
            help(index + 1);
            flag[i] = false;
        }
    }

}


int main() {

    help(1);
    sort(s.begin(), s.end());

    int n;
    while (scanf(" %d", &n) != EOF) {
        for (int i = 0; i < n; ++i) {
            int temp;
            scanf("%d", &temp);
            printf("%ld\n", s[temp - 1]);

        }

    }
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!