1007. Highways(kruskal最小生成树)

来源:互联网 发布:python opencv 与运算 编辑:程序博客网 时间:2024/05/20 06:31

kruskal 最小生成树

#include<iostream>#include<algorithm>using namespace std;int n,_max;int G[501][501];struct edge{    int u;    int v;    int w;  }E[130000]; int father[501];int kruskal(int e);//return the max value of the valid edgebool cmp(edge a,edge b);//compare functionint getfather(int x);//return the father point int main(){    int t;    cin>>t;    while(t--){        _max=-1;//输入矩阵信息         cin>>n;        for(int i=1;i<=n;i++)        for(int j=1;j<=n;j++){            cin>>G[i][j];           }        int e=0;//the number of edges        for(int i=1;i<=n-1;i++)        for(int j=i+1;j<=n;j++){//set the information of edges            E[e].u =i;            E[e].v=j;            E[e++].w=G[i][j];        }         sort(E,E+e,cmp);        cout<<kruskal(e)<<endl;        if(t!=0) cout<<endl;    }    return 0;}bool cmp(edge a,edge b){    return a.w<b.w;}int getfather(int x){    return (father[x]==x)?x:getfather(father[x]); }int kruskal(int e){    for(int i=1;i<=n;i++){ //父节点初始化         father[i]=i;    }    for(int i=0;i<e;i++){        int x=getfather(E[i].u);        int y=getfather(E[i].v);        if(x!=y){            _max=E[i].w;            father[x]=y;    //合并两颗树,只需把y当做x的父亲就可以了          }    }    return _max;}
0 0
原创粉丝点击