답안 #874927

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
874927 2023-11-18T06:23:31 Z The_Samurai 아름다운 순열 (IZhO12_beauty) C++17
100 / 100
711 ms 172884 KB
// #pragma GCC optimize("Ofast,O3")
// #pragma GCC target("avx,avx2")
#include "bits/stdc++.h"

using namespace std;
using ll = long long;

int ter(int n) {
    int cnt = 0;
    while (n) {
        cnt += n % 3 == 1;
        n /= 3;
    }
    return cnt;
}

void solve() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int &x: a) cin >> x;
    vector can(n, vector(n, false));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            can[i][j] = __builtin_popcount(a[i]) == __builtin_popcount(a[j]) or ter(a[i]) == ter(a[j]);
        }
    }
    vector dp(n, vector(1 << n, 0ll));
    for (int i = 0; i < n; i++) dp[i][1 << i] = 1;
    for (int bt = 0; bt < (1 << n); bt++) {
        for (int i = 0; i < n; i++) {
            if (!(bt & (1 << i)) or !dp[i][bt]) continue;
            for (int j = 0; j < n; j++) {
                if (bt & (1 << j)) continue;
                if (can[i][j]) dp[j][bt | (1 << j)] += dp[i][bt];
            }
        }
    }
    ll ans = 0;
    for (int i = 0; i < n; i++) ans += dp[i][(1 << n) - 1];
    cout << ans;
}

int main() {
    cin.tie(0)->sync_with_stdio(false);
#ifdef sunnatov
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int q = 1;
    // cin >> q;
    while (q--) {
        solve();
        cout << '\n';
    }
}
# 결과 실행 시간 메모리 Grader output
1 Correct 0 ms 348 KB Output is correct
2 Correct 0 ms 348 KB Output is correct
3 Correct 0 ms 348 KB Output is correct
4 Correct 0 ms 348 KB Output is correct
5 Correct 0 ms 348 KB Output is correct
6 Correct 1 ms 344 KB Output is correct
7 Correct 0 ms 348 KB Output is correct
8 Correct 1 ms 348 KB Output is correct
9 Correct 1 ms 348 KB Output is correct
10 Correct 1 ms 348 KB Output is correct
11 Correct 7 ms 2392 KB Output is correct
12 Correct 5 ms 2396 KB Output is correct
13 Correct 29 ms 9052 KB Output is correct
14 Correct 148 ms 39516 KB Output is correct
15 Correct 138 ms 39516 KB Output is correct
16 Correct 130 ms 39516 KB Output is correct
17 Correct 154 ms 39768 KB Output is correct
18 Correct 127 ms 39512 KB Output is correct
19 Correct 711 ms 172884 KB Output is correct
20 Correct 587 ms 172880 KB Output is correct