题解:AT_arc224_d [ARC224D] Angst for All Pairs

· · 题解

我们不妨转化一下题意:

构造 k 个 n 位二进制数,其中第 i 个数的第 j 位的实际含义为第 j 张卡片上是否写下了 i。

那么题目中的限制相当于对于任意一对二进制数而言,存在一个数位不同。

即构造出的二进制数互不相同即可。

考虑到写下的数越大代价越大,我们可以这样贪心考虑:让第 k 个二进制数的 \operatorname{popcount} 为 0,让第 k - 1 个至第 k - \binom{n}{1} 个二进制数的 \operatorname{popcount} 为 1,让第 k - \binom{n}{1} - 1 个至第 k - \binom{n}{1} - \binom{n}{2} 个二进制数的 \operatorname{popcount} 为 2,以此类推。

无解当且仅当 2^n < k。

:::success[CODE]

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn = 1e+6 + 6, N = 1e+6, mod = 1e12 + 39;
int T, n, m;
__int128 fac[maxn], inv[maxn];
inline int qpow(__int128 x, int y) {
    __int128 res = 1;
    while (y) {
        if (y & 1) res = res * x % mod;
        x = x * x % mod;
        y >>= 1;
    }
    return res;
}
inline int C(int n, int m) {
    return fac[n] * inv[n - m] % mod * inv[m] % mod;
}
inline int calc(int x) {
    int res = 0;
    while (x) {
        res++;
        x /= 10;
    }
    return res;
}
inline void GOGOGO() {
    cin >> n >> m;
    if ((1ll << min(n, 32ll)) < m) {
        cout << -1 << '\n';
        return;
    }
    int cur = 0, ans = 0, res = 0;
    for (int i = m; i; i--) {
        ans += cur * calc(i);
        res++;
        if (res == C(n, cur)) {
            cur++;
            res = 0;
        }
    }
    cout << ans << '\n';
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    fac[0] = 1;
    for (int i = 1; i <= N; i++) fac[i] = fac[i - 1] * i % mod;
    inv[N] = qpow(fac[N], mod - 2);
    for (int i = N; i; i--) inv[i - 1] = inv[i] * i % mod;
    cin >> T;
    while (T--) GOGOGO();
    return 0;
}

:::