跳到正文

题解

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

Tony2约 3 分钟
原文
文章信息与版本

文章信息

发布
2020年10月12日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 3 分钟
获赞
3
题目
P6824

版本

  1. v1当前

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

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

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

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

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

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

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

用了lowerboundlowerbound,要开O2 QAQ

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