#include<iostream> #include<cstdio> #include<cstring> #include<queue> #define pa pair<int,int> using namespace std; int n,num,dis[101],ans,f[101],head[101]; struct node { int u,v,pre,dis; }e[110*110]; void Add(int from,int to,int dis) { num++; e[num].dis=dis; e[num].u=from; e[num].v=to; e[num].pre=head[from]; head[from]=num; } void Prim() { priority_queue<pa,vector<pa>,greater<pa> >q; dis[1]=0; q.push(make_pair(0,1)); while(!q.empty()) { int k=q.top().second; q.pop(); if(f[k])continue; f[k]=1; ans+=dis[k]; for(int i=head[k];i;i=e[i].pre) if(dis[e[i].v]>e[i].dis) { dis[e[i].v]=e[i].dis; q.push(make_pair(e[i].dis,e[i].v)); } } } int main() { scanf("%d",&n); num=0; int x; memset(dis,127/3,sizeof(dis)); memset(f,0,sizeof(f)); memset(head,0,sizeof(head)); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { scanf("%d",&x); if(i!=j)Add(i,j,x); } ans=0; Prim(); printf("%d ",ans); return 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define ll long long #define maxn 100010 using namespace std; int n,m,fa[maxn],deep[maxn]; ll ans; struct node { int u,v,dis; }e[maxn]; int init() { int x=0;char s;bool f=0;s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=1;s=getchar();} while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();} if(f)return -x;return x; } int cmp(const node &x,const node &y) { return x.dis<y.dis; } int find(int x) { if(x!=fa[x])fa[x]=find(fa[x]); return fa[x]; } void unionn(int x,int y) { if(deep[x]<=deep[y]) { fa[x]=y; if(deep[x]==deep[y]) deep[x]++; } else fa[y]=x; } int main() { n=init();m=init(); int x,y,z; for(int i=1;i<=n;i++)fa[i]=i; for(int i=1;i<=m;i++) { x=init();y=init();z=init(); e[i].u=x;e[i].v=y;e[i].dis=z; } sort(e+1,e+1+m,cmp); for(int i=1;i<=m;i++) { int r1=find(e[i].u); int r2=find(e[i].v); if(r1==r2)continue; ans+=e[i].dis; unionn(r1,r2); } printf("%lld ",ans); return 0; }