da an
2026-10-12 18:15:10
发布于:浙江
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <unordered_map> //map、set 均可
#include <queue>
using namespace std;
typedef long long ll;
const int N = 3e5 + 5;
int n, m, k;
ll ans = 0;
unordered_map<int, int> e[N];
queue< pair<int, int> > q;
#define mp make_pair
#define brac first
#define to second
int fa[N];
ll cnt[N];
void init() {
for (int i = 1; i <= n; i++)
fa[i] = i;
}
int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
void merge(int x, int y) {
x = find(x), y = find(y);
if (x == y)
return;
if (e[x].size() < e[y].size())
swap(x, y);
for (auto it : e[y]) {
if (e[x].count(it.brac))
q.push(mp(e[x][it.brac], it.to));
else
e[x][it.brac] = it.to;
}
fa[y] = x;
e[y].clear();
}
void solve() {
while (!q.empty()) {
pair<int, int> x = q.front();
q.pop();
merge(x.brac, x.to);
}
}
int main(void) {
scanf("%d%d%d", &n, &m, &k);
init();
for (int i = 1, u, v, w; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
swap(u, v);
if (e[u].count(w))
q.push(mp(e[u][w], v));
else
e[u][w] = v;
}
solve();
for (int i = 1; i <= n; i++)
cnt[find(i)];
for (int i = 1; i <= n; i) {
ans += cnt[i] * (cnt[i] - 1) >> 1;
// printf("%lld %lld\n", ans, cnt[i]);
}
printf("%lld\n", ans);
return 0;
}
这里空空如也







有帮助,赞一个