b717困難

異色雙邊界的樹上連通塊

根設為1,每條邊以其子節點代表,求子樹和及 DFS 進出時間。刪掉兩條不同顏色邊後,樹分成三塊,其中同時接觸兩條切邊的中間塊,正好是邊界只有這兩條邊的唯一連通集合。

解題思路

根設為1,每條邊以其子節點代表,求子樹和及 DFS 進出時間。刪掉兩條不同顏色邊後,樹分成三塊,其中同時接觸兩條切邊的中間塊,正好是邊界只有這兩條邊的唯一連通集合。

若子節點 a 是 b 的祖先,中間塊權重為 sum[a]−sum[b];若兩者子樹互不包含,則為 total−sum[a]−sum[b]。枚舉異色切邊對即可取最大並計數。任何合法集合的兩條邊界唯一決定它,因此切邊對與集合是一一對應,無需儲存頂點集合去重。

時間 O(n²)、空間 O(n),n≤1800 時至多約162萬對。Python 順序、子樹和、輸入皆線性;權重和及最佳解數使用 64 位元。

Step-by-step animation

自訂小例:鏈 1—2—3,權重5、−2、8,邊色0、1。

回報動畫錯誤
步驟 1 / 3

步驟 1:計子樹

鏈 1—2—3,權重5、−2、8,邊色0、1。

sum2=6
sum3=8
總和
11

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int n;
    cin >> n;
    vector<ll> s(n);
    for (auto &x : s)
        cin >> x;
    vector<vector<pair<int, int>>> g(n);
    for (int i = 1, u, v, c; i < n; i++) {
        cin >> u >> v >> c;
        g[--u].push_back({--v, c});
        g[v].push_back({u, c});
    }
    vector<int> tin(n), out(n), col(n, -1);
    int timer = 0;
    function<void(int, int)> dfs = [&](int u, int p) {
        tin[u] = timer++;
        for (auto [v, c] : g[u])
            if (v != p) {
                col[v] = c;
                dfs(v, u);
                s[u] += s[v];
            }
        out[u] = timer;
    };
    dfs(0, -1);
    ll best = LLONG_MIN, ways = 0;
    for (int a = 1; a < n; a++)
        for (int b = a + 1; b < n; b++)
            if (col[a] != col[b]) {
                ll z;
                if (tin[a] <= tin[b] && tin[b] < out[a])
                    z = s[a] - s[b];
                else if (tin[b] <= tin[a] && tin[a] < out[b])
                    z = s[b] - s[a];
                else
                    z = s[0] - s[a] - s[b];
                if (z > best)
                    best = z, ways = 1;
                else if (z == best)
                    ways++;
            }
    if (!ways)
        cout << "IMPOSSIBLE\n";
    else
        cout << best << ' ' << ways << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多