题解集合
大家可以互相讨论吖w
原题链接
题解
代码+注释
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 2010, M = 10010;
int n , m;
struct Edge
{
int a,b,w;
bool operator< (const Edge &t) const
{
return w < t.w;
}
}e[M];
int p[N];
int find(int x)
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main()
{
cin >> n >> m;
for(int i = 1;i <= n;i ++) p[i] = i;
int res = 0,k = 0;
for(int i = 0;i < m; i++)
{
int t,a,b,w;
cin >> t >> a >> b >> w;
if(t == 1)//缩点
{
res += w;
p[find(a)] = find(b);
}
else e[k ++] = {a,b,w};
}
sort(e,e + k);
//最小生成树
for(int i = 0;i < k;i ++)
{
int a = find(e[i].a) , b = find(e[i].b), w = e[i].w;
if(a != b)
{
p[a] = b;
res += w;
}
}
cout << res << endl;
return 0;
}