跳到正文

个人记录

CF878D(bitset)

0646Hty约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月28日
篇幅
约 5 分钟

版本

  1. v1当前

题意

初始给 kk 个长为 nn 的序列,qq 次操作,每次操作用两个序列合并一个新序列,使每一位都为两个序列的最大值或最小值。

1<=n<=105,1<=k<=12,1<=q<=1051<=n<=10^5 , 1<=k<=12 , 1<=q<=10^5

sol

kk 很小,发现将每一位上 kk 个数离散为二进制数,第几小就在最低位有几个连续的一,此时 max/minmax/min 就等价于 and/orand/or,可以用 bitsetbitset 维护。

进一步优化,发现本质不同的列只有 2k2^k 个,只处理这些列,计算答案时再对应回去即可。

时间复杂度 O(2kq/w+nk2)O(2^kq/w+nk^2)

先上代码:

C
#include<bits/stdc++.h>
#define re register
#define ll long long
using namespace std;
const int N=1e5+5;
inline int rd(){
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){
		if(ch=='-')f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		x=(x<<3)+(x<<1)+(ch^48);
		ch=getchar();
	}
	return x*f;
}
int n,k,q,t,lans,a[13][N];
int b[N][13],tot,id[N][13];
bitset<4096>s[N];
int main(){
	n=rd(),k=rd(),q=rd(),t=rd();
	for(re int i=1;i<=k;i++)
		for(re int j=1;j<=n;j++)a[i][j]=rd();
	for(re int j=1;j<=n;j++){
		for(re int i=1;i<=k;i++)b[j][i]=a[i][j];//转成n行k列,便于离散
		sort(b[j]+1,b[j]+k+1);
		int len=unique(b[j]+1,b[j]+k+1)-(b[j]+1);
		for(re int i=1;i<=k;i++)a[i][j]=lower_bound(b[j]+1,b[j]+len+1,a[i][j])-b[j];
		//每行离散化
		for(re int i=1;i<=k;i++)
			for(re int p=1;p<=a[i][j];p++)id[j][p]|=(1<<(i-1));//表示第j大列,第p小列
		//n*k小列,本质不同的列只有2^k种,id记录每一小列是哪一种类型,编号0~2^k-1;
	}
	for(re int i=1;i<=k;i++)
		for(re int j=0;j<(1<<k);j++)s[i][j]=(j>>(i-1))&1;//bitset对k个序列都开2^k种不同类型
	tot=k;
	while(q--){
		int op=rd(),x=rd()^(t*lans),y=rd()^(t*lans);
		if(op==1)s[++tot]=s[x]|s[y];
		if(op==2)s[++tot]=s[x]&s[y];
		if(op==3){
			int cnt=0;
			for(re int i=1;i<=k;i++)cnt+=s[x][id[y][i]];
			printf("%d\n",lans=b[y][cnt]);//有多少个一,就是离散后的下标
		}
	}
	return 0;
}

具体说说怎么实现:

来个样例:k=3,n=5k=3,n=5

C
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3

对每一列离散化,使其变为 [1,k][1,k]:

C
1 | 2 | 3 | 3 | 3
3 | 1 | 2 | 2 | 2
2 | 3 | 1 | 1 | 1

进一步将它们转化为末尾为连续 11 的二进制数,(便于用 bitsetbitset 加速):

C
001 | 011 | 111 | 111 | 111
111 | 001 | 011 | 011 | 011
011 | 111 | 001 | 001 | 001

对第一行和第二行取 maxmax(即 andand ):

C
111 | 011 | 111 | 111 | 111

再根据离散数组映射回去即为答案。

但我们发现其中有很多冗余,如第三小组:

C
111
011
->
111

第二小列和第三小列的形式一样,结果也一样。可以看作一个类型。

显然这样本质不同的列有 2k2^k 个。

于是我们可以给每个小列一个编号,然后只处理每个类型的结果。

预处理所有不同的类型:

C
0 1 0 1 0 1 0 1
0 0 1 1 0 0 1 1
0 0 0 0 1 1 1 1
->
0 4 2 6 1 5 3 7

那原序列每一小列的编号为:

C
2 3 7 | 1 5 7 | 4 6 7 | 4 6 7 | 4 6 7

模拟操作:

先预处理每个序列的 bitsetbitset :

C
s[1]: 0 1 0 1 0 1 0 1
s[2]: 0 0 1 1 0 0 1 1
s[3]: 0 0 0 0 1 1 1 1

      0 4 2 6 1 5 3 7

取序列 1,2 的max:

C
s[1]: 0 1 0 1 0 1 0 1
s[2]: 0 0 1 1 0 0 1 1
->
s[4]: 0 1 1 1 0 1 1 1

      0 4 2 6 1 5 3 7

根据原序列每一小列的编号还原序列:

C
2 3 7 | 1 5 7 | 4 6 7 | 4 6 7 | 4 6 7
->
1 1 1 | 0 1 1 | 1 1 1 | 1 1 1 | 1 1 1

有多少个1,离散下标就是几:

C
1 1 1 | 0 1 1 | 1 1 1 | 1 1 1 | 1 1 1
->
3 | 2 | 3 | 3 | 3

离散数组映射:

C
3 | 2 | 3 | 3 | 3
->
5 2 3 4 5

每次只用还原一大列(k个小列),复杂度 O(2kq/w+k/w)O(2^kq/w+k/w)

完结撒花

原文