题解:P17829 [CSP-J 2026] 按位与 / and(民间数据)

· · 题解

从高位向低位按位考虑,贪心优先让答案的高位为 1。

对于每一位算出有多少个数这一位为 1,那么为了让这一位答案为 1,这一位不为 1 的都不能选,剩下的是可选的。但是如果可选的数不足 m 那么这一位答案就不能为 1。贪心的时候记录哪些数不能选即可。

:::success[CODE]

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int maxn = 2e+5 + 5;
int n, m;
int a[maxn];
bool ban[maxn];
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    int ans = 0;
    for (int i = 29; i >= 0; i--) {
        int cnt = 0;
        for (int j = 1; j <= n; j++) {
            if (ban[j]) continue;
            if ((a[j] >> i) & 1) cnt++;
        }
        if (cnt < m) continue;
        // cout << "i: " << i << " cnt: " << cnt << '\n';
        ans += 1ll << i;
        for (int j = 1; j <= n; j++) {
            if (!((a[j] >> i) & 1)) ban[j] = 1;
        }
    }
    cout << ans;
    return 0;
}

:::