题解 P6824 【「EZEC-4」可乐】

· · 题解

提供一种容易想到(?)的想法。

先把可乐从小到大排序,答案肯定是其中一段。

首先枚举聪明值x,然后贪心从高到低按位枚举。

对于每一位,设这一位为i。上一位已经处理到的区间是[l,r]。

设p = lowerbound(a+l, a+r+1, now|(1<<i))-a;,就是可乐的区间[l,r]上第一个第i位为1的位置,now后面解释。

如果(k&(1 << i)) == 0,只有[l,pos-1]和[pos,r]其中一个区间可以保留继续判定,另一个超过了k,判定见代码。

如果(k&(1 << i)) == 1,有[l,pos-1]和[pos,r]其中一个区间可以对答案造成贡献,然后抛弃;另一个区间继续进行判定,因为其中一部分会大于k,另一部分不会。

用了lowerbound,要开O2 QAQ

#include <bits/stdc++.h>
#define R register
using namespace std;
const int N = 1e6+5;
int n, k, a[N], ans;
int read(){
    char ch=getchar();int x=0,f=1;
    while(ch<'0' || ch>'9') {if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int main(){
//  std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//  freopen("in.txt", "r", stdin);
//  freopen("out.out", "w", stdout);
    n = read(), k = read();
    for (int i = 1; i <= n; i++) a[i] = read();
    sort(a+1, a+1+n);
    for (R int x = 0; x <= (1<<20); x++){
        R int sum = 0, l = 1, r = n, now = 0;
        for (R int i = 20; i >= 0; i--){
            R int pos = lower_bound(a+l, a+r+1, now|(1<<i))-a;
            if (!((k>>i)&1)){
                if ((x>>i)&1) l = pos, now |= (1<<i);//1^1==0,1在右边,向右走
                else r = pos-1;//0^0==0,0在左边,向左走
            }else{
                if ((x>>i)&1) sum += r-pos+1, r = pos-1;//1^1==0,右边必然<k,计入答案,抛弃
                else sum += pos-l, l = pos, now |= (1<<i);//同理
            }//now就是从高位走过来的路
        }
        ans = max(sum, ans);
    }
    cout << ans;
    return 0;
}