#include <cstdio> #include <algorithm> using namespace std; struct aaa{ int l,r,w; bool operator < (const aaa& b) const { return w<b.w; } }a[100001]; int fa[100001]; int find(int a) { if (a != fa[a]) return find(fa[a]); return a; } int main() { int n,num = 0,t; scanf("%d%d",&n,&t); for (int i = 0; i<t; i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); a[num].l = x; a[num].r = y; a[num].w = z; num++; } sort(a,a+num); for (int i = 0; i<n; i++) fa[i] = i; int nn = 0,k = 0; long long ans = 0; while(nn<n-1) { int faa = find(a[k].l),fab = find(a[k].r); if (faa != fab) { fa[a[k].l] = fab; fa[faa] = fab; nn++; ans += a[k].w; } k++; } printf("%lld",ans); }
其实发上来意义也不大,只是输入不一样罢了。
题目来源:code[VS]