abc359_G Sum of Tree Distance 題解

Athanasy發表於2024-06-22

題目連結:Atcoder 或者 洛谷

PS:關於桶資訊的刪除,常見的是記錄更改的地方,直接撤銷修改,這樣就可以保證複雜度不會來到 \(O(V)\),其中 \(V\) 為桶的大小。

先考慮暴力,顯然是列舉整棵樹的路徑,這個列舉複雜度顯示是 \(O(n^2)\),還不考慮計算 \(f(i,j)\),考慮使用點分治最佳化列舉複雜度:\(O(n\log{n})\)

接下來考慮如何計算每條路徑的 \(f(i,j)\) ,注意到 \(f(i,j)\)

當且僅當 \(a[i]=a[j]\) 時,答案加上 \(dis(i,j)\),那麼顯然我們至少要維護一個與權值有關的桶資訊。

接下來從點分治的角度思考:

  1. 對於拼鏈,我們選取其他子樹的路徑與當前子樹的路徑進行拼,考慮拼的情況:

我們列舉 \(a[當前子樹的點]\),顯然當 \(a[當前子樹的點]=a[其他子樹的點]\),就需要加上 \(dis(curr,other)\),現在我們考慮其他子樹所有相同值的點都一起計算,那麼顯然我們的公式為:

\[\sum_{a[curr]=a[other]} pre[curr]+pre[other]=cnt[other]\times pre[curr]+\sum pre[other] \]

其中 \(pre\) 表示當前點到列舉的分治中心的距離,而 \(cnt[other]\) 表示其他子樹滿足 \(a[curr]=a[other]\) 的數量,那麼顯然是一個 \(權值\Rightarrow 數量\) 的桶。而顯然 \(\sum pre[other]\) 這個東西,表示的是所有滿足 \(a[curr]=a[other]\) 的字首路徑數量,那麼這個玩意可以用一個類似的桶記錄:\(cntVal[a[curr]]\) 就表示其他子樹中值為 \(a[curr]\) 的字首路徑和,這樣一來就解決了。

  1. 單獨的鏈,我們把根節點視為一個字首路徑為 \(0\)\(pre=0\) 的資訊,這樣一來就可以完美的歸納為上一個情況。
參照程式碼
#include <bits/stdc++.h>

// #pragma GCC optimize(2)
// #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")

#define isPbdsFile

#ifdef isPbdsFile

#include <bits/extc++.h>

#else

#include <ext/pb_ds/priority_queue.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/trie_policy.hpp>
#include <ext/pb_ds/tag_and_trait.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <ext/pb_ds/list_update_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/exception.hpp>
#include <ext/rope>

#endif

using namespace std;
using namespace __gnu_cxx;
using namespace __gnu_pbds;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef tuple<int, int, int> tii;
typedef tuple<ll, ll, ll> tll;
typedef unsigned int ui;
typedef unsigned long long ull;
#define hash1 unordered_map
#define hash2 gp_hash_table
#define hash3 cc_hash_table
#define stdHeap std::priority_queue
#define pbdsHeap __gnu_pbds::priority_queue
#define sortArr(a, n) sort(a+1,a+n+1)
#define all(v) v.begin(),v.end()
#define yes cout<<"YES"
#define no cout<<"NO"
#define Spider ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
#define MyFile freopen("..\\input.txt", "r", stdin),freopen("..\\output.txt", "w", stdout);
#define forn(i, a, b) for(int i = a; i <= b; i++)
#define forv(i, a, b) for(int i=a;i>=b;i--)
#define ls(x) (x<<1)
#define rs(x) (x<<1|1)
#define endl '\n'
//用於Miller-Rabin
[[maybe_unused]] static int Prime_Number[13] = {0, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};

template <typename T>
int disc(T* a, int n)
{
    return unique(a + 1, a + n + 1) - (a + 1);
}

template <typename T>
T lowBit(T x)
{
    return x & -x;
}

template <typename T>
T Rand(T l, T r)
{
    static mt19937 Rand(time(nullptr));
    uniform_int_distribution<T> dis(l, r);
    return dis(Rand);
}

template <typename T1, typename T2>
T1 modt(T1 a, T2 b)
{
    return (a % b + b) % b;
}

template <typename T1, typename T2, typename T3>
T1 qPow(T1 a, T2 b, T3 c)
{
    a %= c;
    T1 ans = 1;
    for (; b; b >>= 1, (a *= a) %= c) if (b & 1) (ans *= a) %= c;
    return modt(ans, c);
}

template <typename T>
void read(T& x)
{
    x = 0;
    T sign = 1;
    char ch = getchar();
    while (!isdigit(ch))
    {
        if (ch == '-') sign = -1;
        ch = getchar();
    }
    while (isdigit(ch))
    {
        x = (x << 3) + (x << 1) + (ch ^ 48);
        ch = getchar();
    }
    x *= sign;
}

template <typename T, typename... U>
void read(T& x, U&... y)
{
    read(x);
    read(y...);
}

template <typename T>
void write(T x)
{
    if (typeid(x) == typeid(char)) return;
    if (x < 0) x = -x, putchar('-');
    if (x > 9) write(x / 10);
    putchar(x % 10 ^ 48);
}

template <typename C, typename T, typename... U>
void write(C c, T x, U... y)
{
    write(x), putchar(c);
    write(c, y...);
}


template <typename T11, typename T22, typename T33>
struct T3
{
    T11 one;
    T22 tow;
    T33 three;

    bool operator<(const T3 other) const
    {
        if (one == other.one)
        {
            if (tow == other.tow) return three < other.three;
            return tow < other.tow;
        }
        return one < other.one;
    }

    T3()
    {
        one = tow = three = 0;
    }

    T3(T11 one, T22 tow, T33 three) : one(one), tow(tow), three(three)
    {
    }
};

template <typename T1, typename T2>
void uMax(T1& x, T2 y)
{
    if (x < y) x = y;
}

template <typename T1, typename T2>
void uMin(T1& x, T2 y)
{
    if (x > y) x = y;
}

constexpr int N = 2e5 + 10;
int siz[N], root, sumSize, maxSon;
bool del[N];
vector<int> child[N];
ll cntVal[N];
ll cnt[N];
int n;
int a[N];
ll res;

inline void dfs(const int curr, const int fa)
{
    siz[curr] = 1;
    for (const int nxt : child[curr]) if (nxt != fa and !del[nxt]) dfs(nxt, curr), siz[curr] += siz[nxt];
}

inline void makeRoot(const int curr, const int fa)
{
    siz[curr] = 1;
    int currSize = 0;
    for (const int nxt : child[curr])
    {
        if (nxt == fa or del[nxt]) continue;
        makeRoot(nxt, curr);
        siz[curr] += siz[nxt];
        uMax(currSize, siz[nxt]);
    }
    uMax(currSize, sumSize - siz[curr]);
    if (currSize < maxSon) maxSon = currSize, root = curr;
}

//權值,字首路徑長
pll dis[N];
int tot;
ll pre[N];

inline void getDis(const int curr, const int fa)
{
    pre[curr] = pre[fa] + 1; //算出字首路徑長
    dis[++tot] = pii(a[curr], pre[curr]); //(值,字首路徑)
    for (const int nxt : child[curr])
    {
        if (nxt == fa or del[nxt]) continue;
        getDis(nxt, curr);
    }
}

inline void cale(const int curr)
{
    vector<pll> add;
    cnt[a[curr]]++; //這個根的值的數量
    pre[curr] = 0; //重置當前點為根的字首路徑長
    for (const auto nxt : child[curr])
    {
        if (del[nxt]) continue;
        tot = 0;
        getDis(nxt, curr);
        //列舉a[other]
        forn(i, 1, tot)
        {
            const auto [v,len] = dis[i];
            add.emplace_back(v, len); //用於刪除桶資訊的
            res += cnt[v] * len + cntVal[v]; //計算公式
        }
        //當前子樹資訊加入到其他子樹中
        forn(i, 1, tot)
        {
            const auto [v,len] = dis[i];
            cntVal[v] += len;
            cnt[v]++;
        }
    }
    //撤銷資訊
    for (const auto [v,len] : add) cnt[v]--, cntVal[v] -= len;
    cnt[a[curr]]--;
}

inline void div(const int curr)
{
    cale(curr);
    del[curr] = true;
    for (const int& nxt : child[curr])
    {
        if (del[nxt]) continue;
        maxSon = sumSize = siz[nxt];
        makeRoot(nxt, 0);
        dfs(nxt, 0);
        div(root);
    }
}

inline void solve()
{
    cin >> n;
    forn(i, 1, n-1)
    {
        int u, v;
        cin >> u >> v;
        child[u].push_back(v);
        child[v].push_back(u);
    }
    forn(i, 1, n) cin >> a[i];
    sumSize = maxSon = n;
    makeRoot(1, 0);
    dfs(root, 0);
    div(root);
    cout << res;
}

signed int main()
{
    // MyFile
    Spider
    //------------------------------------------------------
    // clock_t start = clock();
    int test = 1;
    //    read(test);
    // cin >> test;
    forn(i, 1, test) solve();
    //    while (cin >> n, n)solve();
    //    while (cin >> test)solve();
    // clock_t end = clock();
    // cerr << "time = " << double(end - start) / CLOCKS_PER_SEC << "s" << endl;
}

\[時間複雜度為:\ O(n\log{n}) \]

相關文章