# CF1108F MST Unification

### 题解

#include<bits/stdc++.h>
using namespace std;
#define R register int
#define AC 200100

int n, m, ans;
int fa[AC];
struct node{
int x, y, w;
}way[AC];

bool cmp(node a, node b){return a.w < b.w;}

{
int x = 0; char c = getchar();
while(c > '9' || c < '0') c = getchar();
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x;
}

void pre()
{
for(R i = 1; i <= n; i ++) fa[i] = i;
for(R i = 1; i <= m; i ++)
sort(way + 1, way + m + 1, cmp);
}

int find(int x)
{
if(fa[x] != x) return fa[x] = find(fa[x]);
else return x;
}

void work()
{
//for(R i = 1; i <= m; i ++) printf("%d %d %d\n", way[i].x, way[i].y, way[i].w);
int j;
for(R i = 1; i <= m; i = j + 1)
{

j = i;
for( ; way[j].w == way[i].w; j ++)
if(find(way[j].x) != find(way[j].y)) ans ++;
-- j;
//	printf("%d %d\n", i, ans);
for(R k = i; k <= j; k ++)
{
int u = find(way[k].x), v = find(way[k].y);
if(u != v) ans --, fa[v] = u;//减去不需要加的
}
//	printf("%d %d\n", i, ans);
}
printf("%d\n", ans);
}

int main()
{
//	freopen("in.in", "r", stdin);
pre();
work();
return 0;
}

posted @ 2021-10-14 00:32  ww3113306  阅读(27)  评论(0编辑  收藏  举报