#include<cstdio> #include<algorithm> #include<iostream> #include<vector> #include<queue> #include<string> #define fi first #define se second #define mp make_pair #define pb push_back #define N 2020 using namespace std; int n,a,ojc[N],size[N]; long long wyn; vector<pair<int,pair<int,int> > > kraw; int find(int x){ if(ojc[x]==x) return x; else return ojc[x]=find(ojc[x]); } void uni(int x,int y){ if(size[x]<size[y]){ ojc[x]=y; size[y]+=size[x]; } else{ ojc[y]=x; size[x]+=size[y]; } } int main(){ scanf("%d",&n); for(int i=0;i<=n;i++){ ojc[i]=i; size[i]=1; } for(int i=1;i<=n;i++) for(int j=1;j<=n-i+1;j++){ scanf("%d",&a); kraw.pb(mp(a,mp(i-1,i+j-1))); } sort(kraw.begin(),kraw.end()); for(int i=0;i<kraw.size();i++){ if(find(kraw[i].se.fi)!=find(kraw[i].se.se)){ wyn+=kraw[i].fi; uni(find(kraw[i].se.fi),find(kraw[i].se.se)); } } printf("%lld",wyn); }
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 | #include<cstdio> #include<algorithm> #include<iostream> #include<vector> #include<queue> #include<string> #define fi first #define se second #define mp make_pair #define pb push_back #define N 2020 using namespace std; int n,a,ojc[N],size[N]; long long wyn; vector<pair<int,pair<int,int> > > kraw; int find(int x){ if(ojc[x]==x) return x; else return ojc[x]=find(ojc[x]); } void uni(int x,int y){ if(size[x]<size[y]){ ojc[x]=y; size[y]+=size[x]; } else{ ojc[y]=x; size[x]+=size[y]; } } int main(){ scanf("%d",&n); for(int i=0;i<=n;i++){ ojc[i]=i; size[i]=1; } for(int i=1;i<=n;i++) for(int j=1;j<=n-i+1;j++){ scanf("%d",&a); kraw.pb(mp(a,mp(i-1,i+j-1))); } sort(kraw.begin(),kraw.end()); for(int i=0;i<kraw.size();i++){ if(find(kraw[i].se.fi)!=find(kraw[i].se.se)){ wyn+=kraw[i].fi; uni(find(kraw[i].se.fi),find(kraw[i].se.se)); } } printf("%lld",wyn); } |