POJ - 3764 The xor-longest Path(字典树性质)
生活随笔
收集整理的這篇文章主要介紹了
POJ - 3764 The xor-longest Path(字典树性质)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一棵樹,每條邊上都有一個邊權(quán),現(xiàn)在問能否選擇兩個點,使得其間路徑上的異或和最大
題目分析:直接求肯定是比較復雜的,我們可以轉(zhuǎn)換一下題意,因為是一棵樹,所以n個點肯定互相都連通且無環(huán),我們可以隨便找一個節(jié)點當做根節(jié)點,跑一遍圖的遍歷,順便記錄一下根節(jié)點到每個點的路徑上的異或值,我們用數(shù)組d來儲存,接下來我們?nèi)粝肭髢蓚€點之間的路徑異或,就可以直接用d[i]^d[j]來求了,轉(zhuǎn)換成了任意兩點之間異或最大的問題的,這個經(jīng)典問題如果n*n的話可以跑出答案,但必定超時,所以我們可以用字典樹來優(yōu)化,因為給出的權(quán)值最大只有,所以我們將其用二進制來表示,建立一棵01字典樹,剩下的就是模板題了,為后面的可持久化字典樹做準備:
注意,這個題對時間卡的有點死,用vector當鄰接表的話會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é)點清零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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中石油训练赛 - 01 Matrix(构
- 下一篇: PAT (Advanced Level)