【Luogu1546】最短网络 Agri-Net

problem

solution

codes

//Kruskal
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int n, a[110][110], fa[110], co, ans;
struct side{
    int u, v, w; 
    side (int u, int v, int w):u(u),v(v),w(w){}
    bool operator < (const side b)const{ return w<b.w;}
};
vector<side>e;
int find(int x){ return x==fa[x]? x : fa[x]=find(fa[x]);}
int main(){
    cin>>n;
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
            int x; cin>>x;
            if(i >= j)continue;
            e.push_back(side(i, j, x));
        }
    }
    sort(e.begin(), e.end());
    for(int i = 1; i <= n; i++)fa[i] = i;
    for(int i = 0; i < e.size(); i++){
        if(find(e[i].u) != find(e[i].v)){
            ans += e[i].w;
            fa[find(e[i].u)] = find(e[i].v);
        }
    }
    cout<<ans;
    return 0;
}
posted @ 2018-06-06 21:09  gwj1139177410  阅读(116)  评论(0编辑  收藏  举报
选择