题目大意:已知一个连接了q条路的城镇,求最小生成树。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct data{int l,x,y;}seg[10010]; int r,f[10010],n,l,cnt,x,y,fx,fy,now,p,ans; char c; int sf(int x){return f[x]==x?x:f[x]=sf(f[x]);} void scan(int &x){ while(c=getchar(),c<'0'||c>'9');x=c-'0'; while(c=getchar(),c>='0'&&c<='9')x=x*10+c-'0'; } bool cmp(data a,data b){return a.l<b.l;} int main(){ while(~scanf("%d",&n)){ for(int i=0;i<=n;i++)f[i]=i;ans=p=cnt=now=0; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ scan(l); if(i<j){seg[cnt].l=l;seg[cnt].x=i;seg[cnt++].y=j;} }scan(r);now++; for(int i=0;i<r;i++){ scan(x);scan(y); fx=sf(x);fy=sf(y); if(fx!=fy){f[fx]=fy;now++;} } sort(seg,seg+cnt,cmp); while(now<n){ fx=sf(seg[p].x);fy=sf(seg[p].y); if(fx!=fy){f[fx]=fy;ans+=seg[p].l;now++;} p++; } printf("%d\n",ans); } return 0; }
来源:https://www.cnblogs.com/forever97/p/3582525.html