nssl1230-序列【位运算】

版权声明:原创,未经作者允许禁止转载 https://blog.csdn.net/Mr_wuyongcong/article/details/83445650

正题


题目大意

长度为n的序列,求两个长度大于等于 k k 的连续序列,一个位运算“和”后最大的答案,和“或”后最大的答案。


解题思路

首先 o r or
b = a   o r   x b=a\ or\ x 的话, b a b\geqslant a
所以答案就是所有的或起来

然后 a n d and
b = a   a n d   x b=a\ and\ x 的话, b a b\leqslant a
所以就找长度为k的就好了,维护一个滑动窗口。


code

#include<cstdio>
#include<algorithm>
#define N 1000010
#define W 32
using namespace std;
int n,k,a[N],v[W],max1,max2;
int main()
{
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++)
	{
	    scanf("%d",&a[i]);
	    max1|=a[i];//或的答案
	    for(int j=0;j<W;j++)
	    	v[j]+=(a[i]>>j)&1;//加上新的
	    if(i>=k)
	    {
	    	for(int j=0;j<W;j++)
	    		v[j]-=(a[i-k]>>j)&1;//去掉头 
	    	int ands=0;
	    	for(int j=0;j<W;j++)
	    	  ands+=(v[j]==k)*(1<<j);//计算答案
	    	max2=max(max2,ands);//取最大值
	    }
	}
	printf("%d %d",max1,max2);
}

猜你喜欢

转载自blog.csdn.net/Mr_wuyongcong/article/details/83445650