1. 程式人生 > >K - The Unique MST

K - The Unique MST

target lan stream esp ring bre str lin sizeof

K - The Unique MST

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct nond{
    int x,y,z;
}edge[101*101];
int T,N,M,x,y,z,fa[1000],num,ans[1000];
int tot,bns,k,answer=9999999;
int cmp(nond aa,nond bb){
    
return aa.z<bb.z; } int find(int x){ return fa[x]==x?x:fa[x]=find(fa[x]); } int main(){ cin>>T; while(T--){ cin>>N>>M; tot=0;bns=0; answer=9999999; memset(fa,0,sizeof(fa)); memset(ans,0,sizeof(ans)); for(int i=1
;i<=M;i++){ cin>>x>>y>>z; edge[i].x=x; edge[i].y=y; edge[i].z=z; } sort(edge+1,edge+1+M,cmp); for(int i=1;i<=N;i++) fa[i]=i; for(int i=1;i<=M;i++){ int dx=find(edge[i].x),dy=find(edge[i].y);
if(dx!=dy){ fa[dx]=dy; tot++; ans[tot]=i; bns+=edge[i].z; } if(tot==N-1) break; } for(int i=1;i<=tot;i++){ k=0;num=0; for(int j=1;j<=N;j++) fa[j]=j; sort(edge+1,edge+1+M,cmp); for(int j=1;j<=M;j++){ if(j==ans[i]) continue; int dx=find(edge[j].x),dy=find(edge[j].y); if(dx!=dy){ fa[dx]=dy; num++; k+=edge[j].z; } if(num==N-1) break; } if(num==N-1) answer=min(k,answer); } if(answer==bns) cout<<"Not Unique!"<<endl; else cout<<bns<<endl; } }

K - The Unique MST