Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // OBI 2014 - 2nd Stage - Mapa
- // Lúcio Cardoso
- #include <bits/stdc++.h>
- using namespace std;
- const int maxn = 1e5+10;
- int pai[maxn], peso[maxn];
- bool mark[maxn];
- int Find(int x)
- {
- if (pai[x] == x) return x;
- return pai[x] = Find(pai[x]);
- }
- void Join(int x, int y)
- {
- x = Find(x), y = Find(y);
- if (x == y) return;
- if (peso[x] < peso[y]) swap(x, y);
- pai[y] = x, peso[x] += peso[y];
- }
- int main(void)
- {
- int n;
- scanf("%d", &n);
- for (int i = 1; i <= n; i++)
- pai[i] = i, peso[i] = 1;
- for (int i = 1; i < n; i++)
- {
- int u, v, w;
- scanf("%d %d %d", &u, &v, &w);
- if (!w) Join(u, v);
- }
- vector<int> comp;
- for (int i = 1; i <= n; i++)
- {
- if (!mark[Find(i)])
- {
- mark[Find(i)] = true;
- comp.push_back(peso[Find(i)]);
- }
- }
- int tot = n;
- long long ans = 0;
- for (auto c: comp)
- {
- ans += 1ll*c*(tot-c);
- tot -= c;
- }
- printf("%lld\n", ans);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement