P4151 [WC2011]最大XOR和路径(线性基应用)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                P4151 [WC2011]最大XOR和路径(线性基应用)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                P4151 [WC2011]最大XOR和路徑
思路
如果單純的只是樹形圖,那么答案顯然易見只有一種,也就是從頭到尾的路徑從頭到尾的異或值,但是這里不同的就是有可能在道路上有許多的環。
題目有一個重點提示的一句話
 
理解這句話之后那么我們可以顯然的從1這個位置到達任何一個環,然后回到一號位置,這里面得到的假值將會是所有我們走過的環的異或值,所以我們只要走一條鏈,然后通過貪心地選擇環,最后即可得到我們想要的最大值。
至于如何貪心,這里就要用到線性基了,通常地在線性基地內部求解最大值我們只設置初始ans=1ans = 1ans=1,但是在這里我們應該初始設置ans=dis[n]ans = dis[n]ans=dis[n],然后再跑一遍線性基最大值,即可求得最終的答案。
代碼
/*Author : lifehappy */ #pragma GCC optimize(2) #pragma GCC optimize(3) #include <bits/stdc++.h>#define mp make_pair #define pb push_back #define endl '\n' #define mid (l + r >> 1) #define lson rt << 1, l, mid #define rson rt << 1 | 1, mid + 1, r #define ls rt << 1 #define rs rt << 1 | 1using namespace std;typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii;const double pi = acos(-1.0); const double eps = 1e-7; const int inf = 0x3f3f3f3f;inline ll read() {ll f = 1, x = 0;char c = getchar();while(c < '0' || c > '9') {if(c == '-') f = -1;c = getchar();}while(c >= '0' && c <= '9') {x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();}return f * x; }const int N = 5e4 + 10;int head[N], to[N << 2], nex[N << 2], cnt = 1;ll value[N << 2], dis[N << 2];int visit[N], n, m;struct linearbasis {ll base[64], flag, cnt;void add(ll x) {for(int i = 62; ~i; i--) {if(x >> i & 1) {if(!base[i]) {base[i] = x;return ;}x ^= base[i];}}flag = 1;}ll query_max() {ll ans = dis[n];for(int i = 62; ~i; i--) {if((ans ^ base[i]) > ans) {ans ^= base[i];}}return ans;}ll query_min() {for(int i = 0; i <= 62; i++) {if(base[i]) {return base[i];}}}void rebuild() {cnt = 0;for(int i = 62; i >= 0; i--) {for(int j = i - 1; j >= 0; j--) {if(base[i] >> j & 1) {base[i] ^= base[j];}}}for(int i = 0; i <= 62; i++) {if(base[i]) {ll temp = base[i];base[i] = 0;base[cnt++] = temp;}}}ll query_k(ll k) {k -= flag;if(k == 0) return 0;if(k >= 1ll << cnt) return -1;ll ans = 0;for(int i = 62; ~i; i--) {if(k >> i & 1) {ans ^= base[i];}}return ans;}void init() {memset(base, 0, sizeof base), flag = cnt = 0;} }a;void add(int x, int y, ll w) {to[cnt] = y;nex[cnt] = head[x];value[cnt] = w;head[x] = cnt++; }void dfs(int rt, ll w) {dis[rt] = w, visit[rt] = 1;for(int i = head[rt]; i; i = nex[i]) {if(visit[to[i]]) a.add(w ^ dis[to[i]] ^ value[i]);else dfs(to[i], w ^ value[i]);} }int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);// ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);n = read(), m = read();for(int i = 1; i <= m; i++) {int x = read(), y = read(); ll w = read();add(x, y, w);add(y, x, w);}dfs(1, 0);printf("%lld\n", a.query_max());return 0; }總結
以上是生活随笔為你收集整理的P4151 [WC2011]最大XOR和路径(线性基应用)的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 人工智能数学基础之线性代数(二)
 - 下一篇: 中国电信、中兴通讯展示“5G 驭风云笔电