【題解】ZeroJudge b510: M 皇后 N 城堡

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=b510

#include <bits/stdc++.h>
using namespace std;

int m, n, r[15], c[15], qa[25], qb[25], ca[25], cb[25];

int f(int Q, int C, int i){
    if ((!Q && !C) || i > (m+n)) return 1;
    int ret = 0;
    if (C){
        for (int j = 1; j <= (m+n); j++){
            if (c[j]) continue;
            if (qa[i-j+10] || qb[i+j]) continue;
            c[j] = 1;
            ca[i-j+10]++;
            cb[i+j]++;
            ret += f(Q, C-1, i+1);
            c[j] = 0;
            ca[i-j+10]--;
            cb[i+j]--;
        }
    }
    if (Q){
        for (int j = 1; j <= (m+n); j++){
            if (c[j]) continue;
            if (qa[i-j+10] || qb[i+j]) continue;
            if (ca[i-j+10] || cb[i+j]) continue;
            c[j] = 1;
            qa[i-j+10] = 1;
            qb[i+j] = 1;
            ret += f(Q-1, C, i+1);
            c[j] = 0;
            qa[i-j+10] = 0;
            qb[i+j] = 0;
        }
    }
    return ret;
}

int main(){
    cin >> m >> n;
    cout << f(m, n, 1) << "\n";
}
分享本文 Share with friends