結果

問題 No.3123 Inversion
ユーザー Takao Obi
提出日時 2025-04-19 13:37:52
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 801 ms / 10,000 ms
コード長 2,184 bytes
コンパイル時間 2,031 ms
コンパイル使用メモリ 197,264 KB
実行使用メモリ 134,132 KB
最終ジャッジ日時 2025-04-19 13:38:22
合計ジャッジ時間 23,728 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 21
権限があれば一括ダウンロードができます

ソースコード

diff #

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

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    ll M;
    cin >> T >> M;

    // M==1 のときは常に 0 を出力
    if (M == 1) {
        for (int i = 0; i < T; i++) {
            int _;
            cin >> _;
            cout << 0 << "\n";
        }
        return 0;
    }

    vector<int> Ns(T);
    int maxN = 0;
    for (int i = 0; i < T; i++) {
        cin >> Ns[i];
        maxN = max(maxN, Ns[i]);
    }

    // 1) factorial mod M
    vector<ll> fact(maxN+1);
    fact[0] = 1;
    for (int i = 1; i <= maxN; i++) {
        fact[i] = fact[i-1] * i % M;
    }

    // 2) involutions a[n]
    vector<ll> a(maxN+1);
    a[0] = 1;
    if (maxN >= 1) a[1] = 1;
    for (int n = 2; n <= maxN; n++) {
        a[n] = (a[n-1] + (ll)(n-1) * a[n-2]) % M;
    }

    // 3) pow2 up to floor(maxN/2)
    int halfN = maxN / 2;
    vector<ll> pow2(halfN+1);
    pow2[0] = 1;
    for (int i = 1; i <= halfN; i++) {
        pow2[i] = (pow2[i-1] * 2) % M;
    }

    // 4) P[m] = ∏_{k=1..m}(4k−2) mod M for d[n]
    int quarterN = maxN / 4;
    vector<ll> P(quarterN+1);
    P[0] = 1;
    for (int m = 1; m <= quarterN; m++) {
        P[m] = (P[m-1] * (4LL*m - 2)) % M;
    }

    // 5) H[m] = involutions ∩ 180°-symmetric on m pairs
    vector<ll> H(halfN+1);
    H[0] = 1;
    if (halfN >= 1) H[1] = 2 % M;
    for (int m = 2; m <= halfN; m++) {
        H[m] = (2 * H[m-1] + 2LL*(m-1) * H[m-2]) % M;
    }

    // 6) 出力
    for (int n : Ns) {
        if (n == 1) {
            // 1 % M すれば M>1 のときは 1、M=1 のときは 0
            cout << (1 % M) << "\n";
            continue;
        }
        ll fn = fact[n];
        ll an = a[n];
        int m2 = n / 2;
        ll cn = (fact[m2] * pow2[m2]) % M;
        int m4 = n / 4;
        ll dn = (n % 4 == 0 || n % 4 == 1) ? P[m4] : 0;
        ll hn = H[m2];

        ll S = 0;
        S = (S + 8LL * fn) % M;
        S = (S - 8LL * an % M + M) % M;
        S = (S - 4LL * cn % M + M) % M;
        S = (S - 2LL * dn % M + M) % M;
        S = (S + 6LL * hn) % M;
        cout << S << "\n";
    }

    return 0;
}
0