Problem solution · C++

Total Sum of Interaction Cost in Tree Groups

Total Sum of Interaction Cost in Tree Groups: a C++ solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
152 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Total Sum of Interaction Cost in Tree Groups, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 152 lines of C++ from the credited upstream file total-sum-of-interaction-cost-in-tree-groups.cpp.
  • The implementation visibly relies on sequence storage, hash lookup.
  • 20 loop blocks detected, together with recursive traversal.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeTotal Sum of Interaction Cost in Tree Groups · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(n * g)// Space: O(n * g) // bfsclass Solution {public:    long long interactionCosts(int n, vector<vector<int>>& edges, vector<int>& group) {        vector<vector<int>> adj(n);        for (const auto& e : edges) {            adj[e[0]].emplace_back(e[1]);            adj[e[1]].emplace_back(e[0]);        }        const auto& mx = ranges::max(group);        vector<int64_t> total(mx);        for (const auto& x : group) {            ++total[x - 1];        }        int64_t result = 0;        const auto& bfs = [&]() {            vector<int> order = {0};            vector<int> parent(n, -1);            for (int i = 0; i < size(adj); ++i) {                const auto u = order[i];                for (const auto& v : adj[u]) {                    if (v == parent[u]) {                        continue;                    }                    parent[v] = u;                    order.emplace_back(v);                }            }            return pair(order, parent);        };                const auto& [order, parent] = bfs();        vector<vector<int64_t>> cnt(n, vector<int64_t>(mx));        for (int i = size(order) - 1; i >= 0; --i) {            const auto& u = order[i];            ++cnt[u][group[u] - 1];            for (const auto& v : adj[u]) {                if (u != parent[v]) {                    continue;                }                for (int k = 0; k < size(cnt[v]); ++k) {                    result += cnt[v][k] * (total[k] - cnt[v][k]);                    cnt[u][k] += cnt[v][k];                }            }        }        return result;    }}; // Time:  O(nlogn)// Space: O(n)// bfs, small-to-large mergingclass Solution2 {public:    long long interactionCosts(int n, vector<vector<int>>& edges, vector<int>& group) {        vector<vector<int>> adj(n);        for (const auto& e : edges) {            adj[e[0]].emplace_back(e[1]);            adj[e[1]].emplace_back(e[0]);        }         unordered_map<int, int64_t> total;        for (const auto& x : group) {            ++total[x];        }        int64_t result = 0;        const auto& bfs = [&]() {            vector<int> order = {0};            vector<int> parent(n, -1);            for (int i = 0; i < size(adj); ++i) {                const auto u = order[i];                for (const auto& v : adj[u]) {                    if (v == parent[u]) {                        continue;                    }                    parent[v] = u;                    order.emplace_back(v);                }            }            return pair(order, parent);        };                const auto& [order, parent] = bfs();        vector<unordered_map<int, int64_t>> cnt(n);        for (int i = size(order) - 1; i >= 0; --i) {            const auto& u = order[i];            ++cnt[u][group[u]];            for (const auto& v : adj[u]) {                if (u != parent[v]) {                    continue;                }                for (const auto& [k, c] : cnt[v]) {                    result += c * (total[k] - c);                }                if (size(cnt[v]) > size(cnt[u])) {                    swap(cnt[u], cnt[v]);                }                for (const auto& [k, c] : cnt[v]) {                    cnt[u][k] += c;                }                cnt[v].clear();            }        }        return result;    }}; // Time:  O(nlogn)// Space: O(n)// dfs, small-to-large mergingclass Solution3 {public:    long long interactionCosts(int n, vector<vector<int>>& edges, vector<int>& group) {        vector<vector<int>> adj(n);        for (const auto& e : edges) {            adj[e[0]].emplace_back(e[1]);            adj[e[1]].emplace_back(e[0]);        }         unordered_map<int, int64_t> total;        for (const auto& x : group) {            ++total[x];        }        int64_t result = 0;        const auto dfs = [&](this auto&& dfs, int u, int p) -> unordered_map<int, int64_t> {            unordered_map<int, int64_t> cnt;            ++cnt[group[u]];            for (const auto& v : adj[u]) {                if (v == p) {                    continue;                }                auto new_cnt = dfs(v, u);                for (const auto& [k, c] : new_cnt) {                    result += c * (total[k] - c);                }                if (size(new_cnt) > size(cnt)) {                    swap(cnt, new_cnt);                }                for (const auto& [k, c] : new_cnt) {                    cnt[k] += c;                }            }            return cnt;        };                dfs(0, -1);        return result;    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗