Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma GCC Optimaze("Ofast")
- #pragma GCC target("avx,avx2")
- #include <bits/stdc++.h>
- #define all(x) begin(x), end(x)
- void InitIO(std::string name = "") {
- using namespace std;
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- if (name.size()) {
- assert(freopen((name + ".in").c_str(), "r", stdin));
- assert(freopen((name + ".out").c_str(), "w", stdout));
- }
- }
- using namespace std;
- using ll = long long;
- const int N = 100100;
- struct Edge {
- int f, t, w, id;
- };
- vector<Edge> g[N];
- bool used[N];
- int DfsCount(int from, int par = 0) {
- int ans = 1;
- for (auto& [f, t, w, id] : g[from]) {
- if (!used[id] && par != t) {
- ans += DfsCount(t, f);
- }
- }
- return ans;
- }
- void DfsUsed(int from, int par) {
- for (auto& [f, t, w, id] : g[from]) {
- if (!used[id]) {
- used[id] = true;
- DfsUsed(t, f);
- }
- }
- }
- int main() {
- InitIO();
- int n;
- cin >> n;
- vector<Edge> edges;
- for (int i = 0; i < n - 1; i++) {
- int f, t, w;
- cin >> f >> t >> w;
- f--, t--;
- g[f].push_back(Edge{f, t, w, i});
- g[t].push_back(Edge{t, f, w, i});
- edges.push_back(Edge{f, t, w, i});
- }
- sort(all(edges), [&] (Edge& a, Edge& b) {
- return a.w > b.w;
- });
- long long ans = 0;
- int active = 1;
- for (int i = 0; i < n - 1; i++) {
- auto [f, t, w, id] = edges[i];
- if (used[id]) continue;
- int a = DfsCount(f, t);
- int b = DfsCount(t, f);
- int cur = min(n - active, min(a, b) * 2);
- active += cur;
- ans += (1LL << w) * cur;
- used[id] = true;
- if (a < b) {
- DfsUsed(f, t);
- } else {
- DfsUsed(t, f);
- }
- }
- cout << ans << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement