HRBUST 2072 树上求最大异或路径值
生活随笔
收集整理的這篇文章主要介紹了
HRBUST 2072 树上求最大异或路径值
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一個(gè)很經(jīng)典的套路 思想是 F [u,v] = F[1,u] ^ F[1,v]?
這樣就轉(zhuǎn)化成了n個(gè)數(shù)兩兩異或 求最大值 可以用字典樹來做 每次用當(dāng)前數(shù)去樹中尋求最大xor值 然后把這個(gè)數(shù)字插進(jìn)去 就相當(dāng)于這個(gè)數(shù)字和之前所有的數(shù)字都比較了
發(fā)現(xiàn)自從學(xué)習(xí)了kdtree等一群數(shù)據(jù)結(jié)構(gòu)之后...寫什么都想學(xué)線段樹的寫法..好像很不錯(cuò)啊..?
#include<stdio.h> #include<string.h> #include<algorithm> #include<math.h> #include<map> #include<iostream> #include<string> #include<vector> #include<queue> using namespace std; #define L long long #define pb push_backconst L maxn = 100050 ;L n ; vector<L >q[maxn] ; vector<L >w[maxn] ; L f[maxn] ; bool vis[maxn] ;void bfs(L u) {queue<L > que ;que.push(u) ;que.push(0) ;while(!que.empty()) {L u = que.front() ; que.pop() ;L ff = que.front() ; que.pop() ;for(L i = 0 ; i < q[u].size() ; i ++ ){L v = q[u][i] ;if(vis[v]) {vis[v] = false ;f[v] = ff ^ w[u][i] ;que.push(v) ;que.push(f[v]) ;}}} }L a[50] ; struct node {L l , y ; }b[35 * maxn]; L cnt ; L e[50] ;L did() {L qs = 0 ;L de = 0 ;L res = 0;while(de + 1 <= 32) {L nd = de + 1 ;if(a[nd] == 1) {if(b[qs].l != -1) {res += e[nd] ;qs = b[qs].l ;}else if(b[qs].y != -1) {res += 0 ;qs = b[qs].y ;}else return res ;}else {if(b[qs].y != -1) {res += e[nd] ;qs = b[qs].y ;}else if(b[qs].l != -1) {res += 0 ;qs = b[qs].l ;}else return res ;}de = nd ;}return res ; }void inse() {L qs = 0 ;L de = 0 ;while(de + 1 <= 32) {L nd = de + 1 ;if(a[nd] == 0) {if(b[qs].l == -1) {b[qs].l = (++cnt) ;qs = b[qs].l;b[qs].l = -1 ;b[qs].y = -1 ;}else {qs = b[qs].l ;}}else {if(b[qs].y == -1) {b[qs].y = (++cnt) ;qs = b[qs].y;b[qs].l = -1 ;b[qs].y = -1 ;}else {qs = b[qs].y ;}}de = nd ;} }int main(){while(scanf("%lld",&n) != EOF) {for(L i = 1 ; i <= n ; i ++ )q[i].clear() ;for(L i = 1 ; i <= n ; i ++ )w[i].clear() ;for(L i = 1 ; i < n ; i ++ ){L u , v , c;scanf("%lld%lld%lld",&u,&v,&c) ;q[u].pb(v);q[v].pb(u);w[u].pb(c);w[v].pb(c);}e[32] = 1 ;for(L j = 31 ; j >= 1 ; j -- ) {e[j] = 2*e[j+1] ;}memset(vis,true,sizeof(vis));f[1] = 0 ;vis[1] = false;bfs(1) ;cnt = 0 ;b[cnt].l = -1;b[cnt].y = -1;L ans = 0 ;for(L i = 1 ; i <= n ; i ++ ){L x = f[i];for(L j = 32 ; j >= 1 ; j -- ) {a[j] = x%2 ;x /= 2 ;}L res = did() ;if(ans < res) ans = res ;inse() ;}printf("%lld\n",ans) ;} }// 好像還是第一次寫字典樹 ..
轉(zhuǎn)載于:https://www.cnblogs.com/rayrayrainrain/p/6582392.html
總結(jié)
以上是生活随笔為你收集整理的HRBUST 2072 树上求最大异或路径值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: arcgis for js开发之路径分析
- 下一篇: JSP中四种传递参数的方法