跳到正文

题解

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

DrDuck约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年10月31日
收录
2026年11月1日
更新
2026年11月16日
篇幅
约 2 分钟
获赞
17
题目
P17829

版本

  1. v1当前

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

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

CODE
C++
#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;
}
原文
存档评论27 条抓取于