文章
211
粉丝
1
获赞
1223
访问
164.5k
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200005;
struct node{
int u,v,w;
};
vector<node> g;
bool cmp(node a,node b){
return a.w < b.w;
}
int rt[maxn];
int find(int x){
if (x == rt[x]) return x;
rt[x] = find(rt[x]); // 路径压缩
return rt[x];
}
int main(){
int n,m;
cin >> n >> m;
for(int i=1;i<=n-1;i++){
for(int j=i+1;j<=n;j++)
g.push_back({i,j,0});
}
int a,b;
for(int i=0;i<m;i++){
cin >> a >> b;
for(auto& it:g){
if(it.u == a && it.v == b)
it.w = 1;
}
}
for(int i=1;i<=n;i++)
rt[i] = i;
sort(g.begin(),g.end(),cmp);
int cnt=0,sum=0;
for(auto it:g){
int u = it.u;
int v = it.v;
if(find(u) != find(v)){
cnt++;
sum += it.w;
rt[find(u)] = find(v);
}
if(cnt == n-1)
break;
}
cout << sum;
return 0;
}
登录后发布评论
暂无评论,来抢沙发