#include<iostream> #include<cstdio> #include<algorithm> using namespace std; #define f first #define s second const int size = 3000000; pair<int, pair<int, int> > T[size]; int n, ran[size], sup[size]; int find(int x) { if(sup[x] == x) return x; return sup[x] = find(sup[x]); } int myUnion (int x, int y) { int a = find(x), b = find(y); if(ran[a] < ran[b]) sup[a] = b; else if(ran[a] > ran[b]) sup[b] = a; else { sup[a] = b; ran[b]++; } } int main() { int counter = 0; scanf("%d", &n); for(int i = n; i>0; i--) { for(int j = n-i; j<n; j++) { int a; scanf("%d", &a); T[counter++] = make_pair(a, make_pair(n-i, j+1)); } } sort(T, T+counter); for(int i = 0; i<=n; i++) { ran[i] = 0; sup[i] = i; } long long result = 0; counter = 0; for(int i = 0; counter<n; i++) { int x = T[i].s.f, y = T[i].s.s; x = find(x); y = find(y); if(x != y) { result += (long long) T[i].f; counter++; myUnion(x, y); } } printf("%lld\n", result); return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | #include<iostream> #include<cstdio> #include<algorithm> using namespace std; #define f first #define s second const int size = 3000000; pair<int, pair<int, int> > T[size]; int n, ran[size], sup[size]; int find(int x) { if(sup[x] == x) return x; return sup[x] = find(sup[x]); } int myUnion (int x, int y) { int a = find(x), b = find(y); if(ran[a] < ran[b]) sup[a] = b; else if(ran[a] > ran[b]) sup[b] = a; else { sup[a] = b; ran[b]++; } } int main() { int counter = 0; scanf("%d", &n); for(int i = n; i>0; i--) { for(int j = n-i; j<n; j++) { int a; scanf("%d", &a); T[counter++] = make_pair(a, make_pair(n-i, j+1)); } } sort(T, T+counter); for(int i = 0; i<=n; i++) { ran[i] = 0; sup[i] = i; } long long result = 0; counter = 0; for(int i = 0; counter<n; i++) { int x = T[i].s.f, y = T[i].s.s; x = find(x); y = find(y); if(x != y) { result += (long long) T[i].f; counter++; myUnion(x, y); } } printf("%lld\n", result); return 0; } |