每种w一起考虑,与同层冲突就加
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
int n,m;
struct node
{
int u,v,w;
friend bool operator<(node a,node b)
{
return a.w>b.w;
}
}itm[200005];
int fa[200005];
int gf(int x)
{
if(x!=fa[x])
return fa[x]=gf(fa[x]);
return fa[x];
}
int main() {
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
fa[i]=i;
priority_queue<node> q;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&itm[i].u,&itm[i].v,&itm[i].w);
q.push(itm[i]);
}
int cnt=0,ans=0;
while(!q.empty() && cnt<(n-1))
{
node sta=q.top();
q.pop();
queue<node>q1,q2;
q1.push(sta);
while(!q.empty() && q.top().w==sta.w)
{
q1.push(q.top());
q.pop();
}
while(!q1.empty())
{
node cur=q1.front();
q1.pop();
int f1=gf(cur.u);
int f2=gf(cur.v);
if(f1!=f2)
q2.push(cur);
}
if(!q2.empty())
{
node cur=q2.front();
q2.pop();
int f1=gf(cur.u);
int f2=gf(cur.v);
fa[f1]=f2;
cnt++;
while(!q2.empty())
{
node tp=q2.front();
q2.pop();
f1=gf(tp.u);f2=gf(tp.v);
if(f1==f2)
ans++;
else
fa[f1]=f2,cnt++;
}
}
}
printf("%d\n",ans);
}
return 0;
}