P4570 [BJWC2011]元素(线性基+贪心)

题目链接:https://www.luogu.org/problem/P4570

题目大意:

  给一个序列,在这个序列中选一些数,这些数的魔法值之和要最大,要求这些数中任意几个数的异或和不为0。

解题报告:

  贪心法,按魔法值最大的取,如果能插入线性基,就选中这个数。为什么这样选是对的呢,考虑三组数a[1]=1,v[1]=2,a[2]=2,v[2].y=3,a[3]=3,v[3]=4。其中a[ ]代表该元素的序号,v[ ]代表该元素的价值。

  那么有a[3]^a[1]^a[2]=0,这时我们会发现,要是价值(即总魔法和)最大,应当取a[2]和a[3]两个点,由此便证明了该贪心是正确的。

AC代码:

 1 #include<vector>
 2 #include<cstdio>
 3 #include<iostream>
 4 #include<cmath>
 5 #include<queue>
 6 #include<stack>
 7 #include<cmath>
 8 #include<algorithm>
 9 #define numm ch-48
10 #define pd putchar(' ')
11 #define pn putchar('\n')
12 #define pb push_back
13 #define fi first
14 #define se second
15 #define fre1 freopen("1.txt","r",stdin)
16 #define fre2 freopen("2.txt","w",stdout)
17 using namespace std;
18 template <typename T>
19 void read(T &res) {
20     bool flag=false;char ch;
21     while(!isdigit(ch=getchar())) (ch=='-')&&(flag=true);
22     for(res=numm;isdigit(ch=getchar());res=(res<<1)+(res<<3)+numm);
23     flag&&(res=-res);
24 }
25 template <typename T>
26 void write(T x) {
27     if(x<0) putchar('-'),x=-x;
28     if(x>9) write(x/10);
29     putchar(x%10+'0');
30 }
31 const int maxn=1010;
32 const int N=60;
33 const int inf=0x3f3f3f3f;
34 const int INF=0x7fffffff;
35 typedef long long ll;
36 ll d[70];
37 struct node {
38     ll x;
39     int y;
40     bool operator<(const node &b) const{
41         return y>b.y;
42     }
43 }a[maxn];
44 bool add(ll x) {
45     for(int i=60;~i;i--)
46         if(x&(1LL<<i))
47             if(d[i]) x^=d[i];
48             else {
49                 d[i]=x;
50                 return true;
51             }
52     return false;
53 }
54 int main()
55 {
56     int ans=0,n;
57     read(n);
58     for(int i=1;i<=n;i++)
59         read(a[i].x),read(a[i].y);
60     sort(a+1,a+1+n);
61     for(int i=1;i<=n;i++)
62         if(add(a[i].x)) ans+=a[i].y;
63     write(ans);pn;
64     return 0;
65 }
代码在这里!

 

转载于:https://www.cnblogs.com/wuliking/p/11266983.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值