[Trie] 最長異或值路徑

 異或最值問題是Trie的拿手強項

看到異或應該先想Trie和前綴和


給定一個樹,樹上的邊都具有權值。

樹中一條路徑的異或長度被定義爲路徑上所有邊的權值的異或和:

formula.png

⊕ 爲異或符號。

給定上述的具有n個節點的樹,你能找到異或長度最大的路徑嗎?

輸入格式

第一行包含整數n,表示樹的節點數目。

接下來n-1行,每行包括三個整數u,v,w,表示節點u和節點v之間有一條邊權重爲w。

輸出格式

輸出一個整數,表示異或長度最大的路徑的最大異或和。

數據範圍

1≤n≤1000001≤n≤100000,
0≤u,v<n0≤u,v<n,
0≤w<2310≤w<231

輸入樣例:

4
0 1 3
1 2 4
1 3 6

輸出樣例:

7

樣例解釋

樣例中最長異或值路徑應爲0->1->2,值爲7 (=3 ⊕ 4)

翻譯一下題目, 給一個無向無環圖 求兩點間路徑權最大

思路:

如圖所示, 將無向無環圖轉換爲一顆樹, 以任意一點做根均滿足定義

則有:

1 - 3點的異或路徑是 val[1 - 3]

2 - 3點的異或路徑是 val[1 - 2] ^ val[1- 3]

3 - 4點的異或路徑是val[3 - 4] ^ val[3 - 5]

不難發現, 結合異或前綴和的性質

 用D數組保存從樹根到所有點的異或和

則任意兩點間的路徑由於其唯一性(樹的性質)都可以O(1)的求出

因此用Trie貪心優化求最值即可


代碼

/*
    Zeolim - An AC a day keeps the bug away
*/

//#pragma GCC optimize(2)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <sstream>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef long double ld;
const int INF = 0x3f3f3f3f;
const ld PI = acos(-1.0);
const ld E = exp(1.0);

const int MAXN = 1e7 + 10;

std::vector< pair <ll, ll> > edge[MAXN];

ll D[MAXN] = {0};

bool used[MAXN] = {0};

int trie[MAXN][2] = {0}, cnt = 1;

void dfs(int now)
{
    if(!used[now])
    {
        used[now] = true;

        for(int i = 0; i < edge[now].size(); ++i)
        {
            int to = edge[now][i].first, val = edge[now][i].second;

            if(!used[to])
            {
                D[to] = D[now] ^ val;

                dfs(to);
            }
        }
    }
}

void insert(ll x)
{
    int to = 1;

    for(int i = 31; i >= 0; --i)
    {
        int val = x >> i & 1;

        if( !trie[to][val])
            trie[to][val] = ++cnt;
        to = trie[to][val];
    }
}

ll serch(ll x)
{
    ll ret = 0;

    int to = 1;
    
    for(int i = 31; i >= 0; --i)
    {
        int val = x >> i & 1;

        if(trie[to][val ^ 1])
            ret += (ll(1) << i), to = trie[to][val ^ 1];
        else
            to = trie[to][val];
    }

    return ret;
}

int main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(0);     cout.tie(0);
    //freopen("D://test.in", "r", stdin);
    //freopen("D://test.out", "w", stdout);

    ll n, from, to, val;

    ll ans = -1;

    cin >> n;

    for(int i = 1; i < n; ++i)
    {
        cin >> from >> to >> val;
        
        ++from, ++to;

        edge[from].push_back(make_pair(to, val));
        edge[to].push_back(make_pair(from, val));
    }  

    dfs(1);

    for(int i = 1; i <= n; ++i)
    {
        ans = max(ans, serch(D[i]));
        insert(D[i]);
    }

    cout << ans << '\n';

    
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章