HGerdd @ 2024-02-01 17:38:39
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct road
{
int a,b;
int w;
};
int find(vector<int> p, int x)
{
if(x != p[x])
{
x = find(p,p[x]);
}
return x;
}
bool cmp(road a, road b)
{
return a.w < b.w;
}
int main()
{
long long n,m;
cin >> n >> m;
vector<road> G(m);
for (int i = 0; i < m; i++)
{
cin >> G[i].a >> G[i].b >> G[i].w;
}
sort(G.begin(),G.end(),cmp);
vector<int> p(n+1);
for (int i = 1; i < n+1; i++)
{
p[i] = i;
}
int sum = 0;
for (int i = 0; i < m; i++)
{
int a = G[i].a,b = G[i].b,w = G[i].w;
int fa = find(p,a), fb = find(p,b);
if(fa != fb)
{
p[fa] = fb;
sum += w;
}
}
cout << sum;
return 0;
}
by Yuzilihhh @ 2024-02-01 17:54:06
@HGerdd 首先纠正一下,是TLE,不是TIL
1.题目中说,若此图不连通输出orz
,所以需要一个变量看看他记录了几条边,如果orz
by Yuzilihhh @ 2024-02-01 17:54:40
不好意思,Latex打错了,是小于n-1