日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

POJ - 3764 The xor-longest Path(字典树性质)

發(fā)布時(shí)間:2024/4/11 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 POJ - 3764 The xor-longest Path(字典树性质) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目鏈接:點(diǎn)擊查看

題目大意:給出一棵樹,每條邊上都有一個(gè)邊權(quán),現(xiàn)在問能否選擇兩個(gè)點(diǎn),使得其間路徑上的異或和最大

題目分析:直接求肯定是比較復(fù)雜的,我們可以轉(zhuǎn)換一下題意,因?yàn)槭且豢脴?#xff0c;所以n個(gè)點(diǎn)肯定互相都連通且無環(huán),我們可以隨便找一個(gè)節(jié)點(diǎn)當(dāng)做根節(jié)點(diǎn),跑一遍圖的遍歷,順便記錄一下根節(jié)點(diǎn)到每個(gè)點(diǎn)的路徑上的異或值,我們用數(shù)組d來儲存,接下來我們?nèi)粝肭髢蓚€(gè)點(diǎn)之間的路徑異或,就可以直接用d[i]^d[j]來求了,轉(zhuǎn)換成了任意兩點(diǎn)之間異或最大的問題的,這個(gè)經(jīng)典問題如果n*n的話可以跑出答案,但必定超時(shí),所以我們可以用字典樹來優(yōu)化,因?yàn)榻o出的權(quán)值最大只有,所以我們將其用二進(jìn)制來表示,建立一棵01字典樹,剩下的就是模板題了,為后面的可持久化字典樹做準(zhǔn)備:

注意,這個(gè)題對時(shí)間卡的有點(diǎn)死,用vector當(dāng)鄰接表的話會T,只能手寫鄰接表了

代碼:

#include<iostream> #include<cstdlib> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<climits> #include<cmath> #include<cctype> #include<stack> #include<queue> #include<list> #include<vector> #include<set> #include<map> #include<sstream> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e5+100;int trie[N*32][2];int d[N];int head[N];int cnt,tot;struct Node {int to,w,next; }edge[N*2];void addedge(int u,int v,int w) {edge[tot].to=v;edge[tot].w=w;edge[tot].next=head[u];head[u]=tot++;edge[tot].to=u;edge[tot].w=w;edge[tot].next=head[v];head[v]=tot++; }int newnode()//動態(tài)初始化 {cnt++;trie[cnt][0]=trie[cnt][1]=0;return cnt; }void insert(int x) {int pos=0;for(int i=31;i>=0;i--){int to=(x>>i)&1;if(!trie[pos][to])trie[pos][to]=newnode();pos=trie[pos][to];} }int search(int x) {int pos=0;int ans=0;for(int i=31;i>=0;i--){int to=(x>>i)&1;if(trie[pos][!to]){pos=trie[pos][!to];ans|=(1<<i);}elsepos=trie[pos][to];}return ans; }void dfs(int u,int fa,int k) {d[u]=k;for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;if(v==fa)continue;dfs(v,u,k^w);} }void init() {memset(head,-1,sizeof(head));trie[0][1]=trie[0][0]=0;//記得給根節(jié)點(diǎn)清零tot=cnt=0; }int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);int n;while(scanf("%d",&n)!=EOF){init();for(int i=1;i<n;i++){int u,v,w;scanf("%d%d%d",&u,&v,&w);u++,v++;addedge(u,v,w);}dfs(1,-1,0);for(int i=1;i<=n;i++)insert(d[i]);int ans=0;for(int i=1;i<=n;i++)ans=max(ans,search(d[i]));printf("%d\n",ans);}return 0; }

?

總結(jié)

以上是生活随笔為你收集整理的POJ - 3764 The xor-longest Path(字典树性质)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。