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

· · 题解

可能你在 P17828 的题解中已经看到我了

插曲

在上午那个令人不平静的机房里,我暴力+特判,写了 90+ 行, 1500+ 字数的代码。而目标仅仅是为了, 拿 65 分

性质
a&b<=min(a,b)

二进制+贪心

从最高位(29 位)往低位依次尝试:

  1. 设当前已经拼出来的答案是 ans
  2. 尝试把当前这一位变成 1:cand = ans | (1 << bit)
  3. 统计数组里有多少个数 x 满足 x & cand == cand ,也就是这个数包含我们目前所有选定的 1
  4. 如果数量 >= m :说明我们可以选出 M 个,这一位可以保住 1,ans = cand ;否则这一位只能是 0,跳过

复杂度: O(30n)

标程 :

#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 2e5 + 5;
int a[MAXN];
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int ans = 0;
    // 从29位到0位
    for (int bit = 29; bit >= 0; bit--) {
        int cand = ans | (1 << bit);
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            if ((a[i] & cand) == cand) {
                cnt++;
            }
        }
        if (cnt >= m) {
            ans = cand;
        }
    }
    cout << ans << endl;
    return 0;
}

完结撒花