#include <cstdio> #include <vector> #include <iostream> #include <algorithm> #define MP make_pair #define f first #define s second using namespace std; int tab[3000]; vector < pair < int, pair<int, int> > > V; int FIND(int x){ if(x==tab[x] ) return x; tab[x]=tab[FIND(tab[x])]; return tab[x]; } void UNION(int a, int b){ if (FIND(a)!=FIND(b)) tab[FIND(a)]=FIND(b); return ; } int main() { //ios_base::sync_with_stdio(0); int n, pom, skladowe; //cin>>n; scanf("%d", &n); skladowe = n+1; for(int i=1; i<=n+1; i++) tab[i]=i; for(int i=1; i<=n; i++) for(int j=i+1; j<=n+1; j++) { scanf("%d", &pom); //cin>>pom; V.push_back(MP(pom, MP(i, j))); } sort(V.begin(), V.end()); long long koszt=0, k; for(int i=0; skladowe>1; i++) { if (FIND(V[i].s.f) != FIND(V[i].s.s)) { skladowe--; k=V[i].f; koszt+=k; UNION(V[i].s.f, V[i].s.s); } } cout<<koszt; // system("PAUSE"); return 0; } /* 5 1 2 3 4 5 4 3 2 1 3 4 5 2 1 5 6 1 7 2 7 8 10 9 3 4 11 7 4 8 9 13 9 6 10 11 5 13 */
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #define MP make_pair #define f first #define s second using namespace std; int tab[3000]; vector < pair < int, pair<int, int> > > V; int FIND(int x){ if(x==tab[x] ) return x; tab[x]=tab[FIND(tab[x])]; return tab[x]; } void UNION(int a, int b){ if (FIND(a)!=FIND(b)) tab[FIND(a)]=FIND(b); return ; } int main() { //ios_base::sync_with_stdio(0); int n, pom, skladowe; //cin>>n; scanf("%d", &n); skladowe = n+1; for(int i=1; i<=n+1; i++) tab[i]=i; for(int i=1; i<=n; i++) for(int j=i+1; j<=n+1; j++) { scanf("%d", &pom); //cin>>pom; V.push_back(MP(pom, MP(i, j))); } sort(V.begin(), V.end()); long long koszt=0, k; for(int i=0; skladowe>1; i++) { if (FIND(V[i].s.f) != FIND(V[i].s.s)) { skladowe--; k=V[i].f; koszt+=k; UNION(V[i].s.f, V[i].s.s); } } cout<<koszt; // system("PAUSE"); return 0; } /* 5 1 2 3 4 5 4 3 2 1 3 4 5 2 1 5 6 1 7 2 7 8 10 9 3 4 11 7 4 8 9 13 9 6 10 11 5 13 */ |