結果

問題 No.1846 Good Binary Matrix
ユーザー 👑 potato167
提出日時 2025-04-17 11:11:04
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 126 ms / 2,000 ms
コード長 1,598 bytes
コンパイル時間 2,425 ms
コンパイル使用メモリ 196,160 KB
実行使用メモリ 26,568 KB
最終ジャッジ日時 2025-04-17 11:11:09
合計ジャッジ時間 4,900 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 35
権限があれば一括ダウンロードができます

ソースコード

diff #

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

// Fast exponentiation
ll modpow(ll a, ll e) {
    ll res = 1 % MOD;
    a %= MOD;
    while (e > 0) {
        if (e & 1) res = res * a % MOD;
        a = a * a % MOD;
        e >>= 1;
    }
    return res;
}

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

    int H, W;
    cin >> H >> W;
    // We will perform inclusion-exclusion over the smaller dimension
    bool swapHW = false;
    if (H > W) {
        swap(H, W);
        swapHW = true;
    }
    // Now H <= W
    int N = H;

    // Precompute factorials and inv factorials up to N
    vector<ll> fact(N+1,1), invfact(N+1,1);
    for(int i = 1; i <= N; i++){
        fact[i] = fact[i-1] * i % MOD;
    }
    invfact[N] = modpow(fact[N], MOD-2);
    for(int i = N; i >= 1; i--){
        invfact[i-1] = invfact[i] * i % MOD;
    }

    // Precompute 2^k for k up to max(H,W)
    int M = max(H, W);
    vector<ll> pow2(M+1,1);
    for(int i = 1; i <= M; i++){
        pow2[i] = (pow2[i-1] * 2) % MOD;
    }

    ll ans = 0;
    // Sum_{i=0..H} (-1)^i C(H,i) * (2^{H-i} - 1)^W
    for(int i = 0; i <= H; i++){
        // sign
        ll sign = (i % 2 == 0 ? 1 : MOD-1);
        // C(H,i)
        ll comb = fact[H] * invfact[i] % MOD * invfact[H - i] % MOD;
        // base = 2^{H-i} - 1
        ll base = (pow2[H - i] + MOD - 1) % MOD;
        // power = base^W
        ll pw = modpow(base, W);
        ll term = sign * comb % MOD * pw % MOD;
        ans = (ans + term) % MOD;
    }

    cout << ans << "\n";
    return 0;
}
0