P4570 [BJWC2011]元素 线性基上贪心

n个物品,有编号和价值两个属性,如果多个物品之间编号异或为0,那么他们就会消失。求一个子集,使得总价值最大。

根据线性基的性质 假设我有3个物品的编号异或为0,那么这三个物品无论以什么样的顺序插入线性基,最后一个一定是无法插入的,那么有个显而易见的贪心策略:把物品按价值降序排序,如果一个物品能插入线性基,我们就加上它的价值,否则忽略。

#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+10;
typedef long long ll;
ll d[66];
struct node{
	ll num,magic;
	bool operator < (const node &a){
		return magic>a.magic;
	}
}q[N];
bool ins(ll x){
	for(int i = 63; i >= 0; i--){
		if((x>>i)&1){
			if(d[i]==0){
				d[i]=x;
				//printf("d[%d]=%d\n",i,d[i]);
				return true;
			}else x^=d[i];
		}
	}
	return false;
}
int main(){
	int n;
	scanf("%d",&n);
	for(int i = 1; i <= n; i++)
		scanf("%lld%lld",&q[i].num,&q[i].magic);
	sort(q+1,q+1+n);
	ll ans = 0;
	for(int i = 1; i <= n; i++){
		if(ins(q[i].num))
		ans+=q[i].magic; 
	}
	printf("%lld\n",ans);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章