1. 程式人生 > >P4570 [BJWC2011]元素 線性基 + 貪心

P4570 [BJWC2011]元素 線性基 + 貪心

amp gcc getchar ret long 從大到小 for pri nbsp


題意

給定n個物品,每個物品有一個編號和價值,問如何取使得拿到的物品價值總和最大,並且取得物品的編號的子集異或和不能為0。

思路

這是個貪心,我們先按照價值從大到小排序,然後貪心地取,如果當前要取的物品的編號和之前取的存在異或為0的情況,我們就丟棄這個物品,否則加入。判斷異或為0可以用線性基來做。
具體證明參考

技術分享圖片
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize(4)

#include <algorithm>
#include  
<iterator> #include <iostream> #include <cstring> #include <cstdlib> #include <iomanip> #include <bitset> #include <cctype> #include <cstdio> #include <string> #include <vector> #include <stack> #include
<cmath> #include <queue> #include <list> #include <map> #include <set> #include <cassert> using namespace std; #define lson (l , mid , rt << 1) #define rson (mid + 1 , r , rt << 1 | 1) #define debug(x) cerr << #x << " = " << x << "\n"; #define
pb push_back #define pq priority_queue typedef long long ll; typedef unsigned long long ull; typedef long double ld; //typedef __int128 bll; typedef pair<ll ,ll > pll; typedef pair<int ,int > pii; typedef pair<int,pii> p3; //priority_queue<int> q;//這是一個大根堆q //priority_queue<int,vector<int>,greater<int> >q;//這是一個小根堆q #define fi first #define se second //#define endl ‘\n‘ #define boost ios::sync_with_stdio(false);cin.tie(0) #define rep(a, b, c) for(int a = (b); a <= (c); ++ a) #define max3(a,b,c) max(max(a,b), c); #define min3(a,b,c) min(min(a,b), c); const ll oo = 1ll<<17; const ll mos = 0x7FFFFFFF; //2147483647 const ll nmos = 0x80000000; //-2147483648 const int inf = 0x3f3f3f3f; const ll inff = 0x3f3f3f3f3f3f3f3f; //18 const int mod = 1e9; const double esp = 1e-8; const double PI=acos(-1.0); const double PHI=0.61803399; //黃金分割點 const double tPHI=0.38196601; template<typename T> inline T read(T&x){ x=0;int f=0;char ch=getchar(); while (ch<0||ch>9) f|=(ch==-),ch=getchar(); while (ch>=0&&ch<=9) x=x*10+ch-0,ch=getchar(); return x=f?-x:x; } inline void cmax(int &x,int y){if(x<y)x=y;} inline void cmax(ll &x,ll y){if(x<y)x=y;} inline void cmin(int &x,int y){if(x>y)x=y;} inline void cmin(ll &x,ll y){if(x>y)x=y;} /*-----------------------showtime----------------------*/ const int maxn = 1009; struct node{ ll id; int val; }a[maxn]; bool cmp(node a,node b){ return a.val > b.val; } ll p[109]; bool check(ll x){ for(int i=60; i>=0; i--) { if((x & (1ll << i) ) > 0) { if(p[i] >-1) x ^= p[i]; else { p[i] = x; return true; } } } return false; } int main(){ memset(p, -1, sizeof(p)); int n; scanf("%d", &n); for(int i=1; i<=n; i++) { scanf("%lld%d", &a[i].id, &a[i].val); } sort(a+1, a+1+n,cmp); int sum = 0; for(int i=1; i<=n; i++) { if(check(a[i].id)) sum += a[i].val; } printf("%d\n", sum); return 0; }
View Code

P4570 [BJWC2011]元素 線性基 + 貪心