标签:
两个正整数N,M。(1 <= N <= 10^5, N <= M <= 2 * 10^5) 接下来M行,每一行有三个整数A, B, V。(1 <= A, B <= N, INT_MIN <= V <= INT_MAX) 保证输入数据合法。
输出一个正整数R,表示符合条件的魔法阵的魔力值之和。
4 6 1 2 3 1 3 1 1 4 7 2 3 4 2 4 5 3 4 6
12
#include<iostream> #include<algorithm> #include<cstdio> #include<queue> #include<map> #include<vector> #include<cstring> #include<cmath> using namespace std; typedef long long ll; const int inf =0x3f3f3f3f; const double pi = acos(-1.0); const int N = 3e5 + 10; int root[N]; struct node { int x, y; ll w; } p[N]; int Find(int x) { return x == root[x]?x:root[x] = Find(root[x]); } int cmp1(node a, node b) { return a.w<b.w; } int cmp2(node a, node b) { return a.w>b.w; } int main() { int n, m; scanf("%d%d", &n, &m); for(int i = 0; i<m; i++) { scanf("%d%d%I64d", &p[i].x, &p[i].y, &p[i].w); } for(int i = 0; i<=n; i++) root[i] = i; sort(p, p+m, cmp1); int k, num = 0; ll last = -inf*100LL; for(int i = 0; i<m; i++) { int a = Find(p[i].x), b = Find(p[i].y); if(a!=b) { num++; last = max(last, p[i].w); root[a] = b; } if(num == n-1) { break; } } for(int i = 0; i<=n; i++) root[i] = i; for(int i = 0; i<m; i++) { if(p[i].w>last) { k = i; break; } } sort(p, p+k, cmp2); ll ans = 0; num = 0; for(int i = 0; i<k; i++) { int a = Find(p[i].x), b = Find(p[i].y); if(a!=b) { num++; ans += p[i].w; root[a] = b; } if(num == n-1) break; } cout<<ans<<endl; return 0; }
标签:
原文地址:http://blog.csdn.net/dml_96/article/details/51329902