
我在这里使用的是kruskal,先按权值排序,然后贪心
代码见下
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
|
#include <cstdio> #include <algorithm> using namespace std; int n,m; long long ans; struct { int x; int y; int z; }a[100005]; int s[100055]; int fa[100005]; int cnt=0; bool cmp(const node &x,const node &y) { return x.z<y.z; } int find(int x) { if(fa[x]==x) { return x; } return fa[x]=find(fa[x]); } void kkk() { int f1; int f2; int k=0; for(int i=1;i<=n;i++) fa[i]=i; for(int i=1;i<=cnt;i++) { f1=find(a[i].x); f2=find(a[i].y); if(f1!=f2) { ans=ans+a[i].z; fa[f1]=f2; k++; if(k==n-1) break; } } } int main(){ cin>>n; for(int i=1;i<=n;i++) { scanf("%d",&s[i]); } for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { scanf("%d",&a[++cnt].z); a[cnt].x=i; a[cnt].y=j; } a[++cnt].x=i; a[cnt].y=n+1; a[cnt].z=s[i]; } n++; sort(a+1,a+1+cnt,cmp); kkk(); cout<<ans<<endl; }
|
近期评论