Submission #28043827


Source Code Expand

#include <algorithm>
#include <iostream>
#include <vector>

struct UnionFind {
  std::vector<int> parent_or_size;
  int cnt;

  UnionFind(int n) : parent_or_size(n, -1), cnt(n) {}

  void unite(int x, int y) {
    x = find_root(x);
    y = find_root(y);
    if (x == y) {
      return;
    }
    if (-parent_or_size[x] < -parent_or_size[y]) {
      std::swap(x, y);
    }
    parent_or_size[x] += parent_or_size[y];
    parent_or_size[y] = x;
    cnt--;
  }
  bool is_same_root(int x, int y) { return find_root(x) == find_root(y); }
  int find_root(int x) {
    if (parent_or_size[x] < 0) {
      return x;
    }
    return parent_or_size[x] = find_root(parent_or_size[x]);
  }
  int size(int x) { return -parent_or_size[find_root(x)]; }
};

struct Edge {
  int u, v;
  long long w;
  Edge() {}
  Edge(int x, int y, long long z) : u(x), v(y), w(z) {}
};

bool comp(Edge &a, Edge &b) { return a.w < b.w; }

int main() {
  int N;
  std::cin >> N;

  std::vector<Edge> edges(N - 1);
  for (int i = 0; i < N - 1; i++) {
    int u, v, w;
    std::cin >> u >> v >> w;
    edges[i] = Edge(u - 1, v - 1, w);
  }

  std::sort(edges.begin(), edges.end(), comp);

  UnionFind uf_tree(N);

  long long ans = 0;
  for (int i = 0; i < N - 1; i++) {
    int u = edges[i].u;
    int v = edges[i].v;
    long long w = edges[i].w;
    ans += w * (long long)uf_tree.size(u) * (long long)uf_tree.size(v);
    uf_tree.unite(u, v);
  }

  std::cout << ans << "\n";

  return 0;
}

Submission Info

Submission Time
Task D - Sum of Maximum Weights
User kira924age
Language C++ (GCC 9.2.1)
Score 400
Code Size 1526 Byte
Status AC
Exec Time 83 ms
Memory 5052 KiB

Judge Result

Set Name Sample All
Score / Max Score 0 / 0 400 / 400
Status
AC × 2
AC × 20
Set Name Test Cases
Sample example_00.txt, example_01.txt
All example_00.txt, example_01.txt, line.txt, linelike_00.txt, linelike_01.txt, linelike_02.txt, rand_00.txt, rand_01.txt, rand_02.txt, rand_03.txt, rand_04.txt, rand_05.txt, rand_06.txt, rand_07.txt, rand_08.txt, rand_09.txt, star.txt, starlike_00.txt, starlike_01.txt, starlike_02.txt
Case Name Status Exec Time Memory
example_00.txt AC 9 ms 3628 KiB
example_01.txt AC 2 ms 3548 KiB
line.txt AC 79 ms 4916 KiB
linelike_00.txt AC 81 ms 5016 KiB
linelike_01.txt AC 81 ms 4968 KiB
linelike_02.txt AC 79 ms 4916 KiB
rand_00.txt AC 82 ms 5040 KiB
rand_01.txt AC 79 ms 5000 KiB
rand_02.txt AC 33 ms 3728 KiB
rand_03.txt AC 61 ms 4332 KiB
rand_04.txt AC 53 ms 4280 KiB
rand_05.txt AC 13 ms 3560 KiB
rand_06.txt AC 57 ms 4488 KiB
rand_07.txt AC 53 ms 4192 KiB
rand_08.txt AC 7 ms 3580 KiB
rand_09.txt AC 42 ms 4008 KiB
star.txt AC 82 ms 5008 KiB
starlike_00.txt AC 78 ms 4948 KiB
starlike_01.txt AC 81 ms 5052 KiB
starlike_02.txt AC 83 ms 4944 KiB