贪心+线性基--bzoj2460: [BeiJing2011]元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sizeof_you/article/details/85220359

传送门

突然发现自己忘了线性基怎么写了···于是复习一下

裸的线性基,要权值最大就按权值排序然后一个一个加。

线性基: a x a_x 的二进制第 x x 位为1,构造方法就是从高位到低位扫描每个数 p p ,如果 x x 这一位是 1 1 ,并且 a x = 0 a_x=0 ,那么让 a x = p a_x=p ,跳出循环,否则就让 p p ^ = a x =a_x

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define maxn 1005
#define LL long long
using namespace std;

template<class T>inline void rd(T &x){
	x=0; short f=1; char c=getchar();
	while(c<'0' || c>'9') f=c=='-'?0:1,c=getchar();
	while(c<='9' && c>='0') x=x*10+(c^'0'),c=getchar();
	x=f?x:-x;
}

int n,ans;
LL a[65];
struct Stone{
	LL num; int val;
	bool operator <(const Stone &x) const{
		return val>x.val;
	}
}p[maxn];

int main(){
	rd(n);
	for(int i=1;i<=n;i++){
		rd(p[i].num); rd(p[i].val);
	}
	sort(p+1,p+n+1);
	for(int i=1;i<=n;i++)
		for(int j=60;j>=0;j--)
			if((1LL<<j)&p[i].num){
				if(!a[j]) {a[j]=p[i].num,ans+=p[i].val;break;}
				else p[i].num^=a[j];
			}
	printf("%d\n",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sizeof_you/article/details/85220359
今日推荐