Agri-Net 1558 Agri-Net

来源:互联网 发布:sift python 编辑:程序博客网 时间:2024/06/06 01:38

PS: 简单的最小生成树, 省赛热身。

#include <iostream>#include <cstdio>#include <algorithm>#include <vector>using namespace std;const int maxn = 110;struct edges {    int u, v, w;};int n;vector<edges> G;int f[maxn+5];int getFather(int x) {    if(x==f[x]) return x;    else return f[x] = getFather(f[x]);}bool cmp(edges a, edges b) {     return a.w < b.w;}int work() {    sort(G.begin(), G.end(), cmp);    for(int i = 1; i < maxn; i++) f[i] = i;    int cnt = 0;    int ans = 0;    edges t;    for(int i = 0; i < (int)G.size(); i++) {        t = G[i];        int t1 = getFather(t.u);        int t2 = getFather(t.v);        if(t1!=t2) {            f[t1] = t2;            ans += t.w;            cnt++;            if(cnt==n-1) break;        }    }    return ans;}int main(){    int tmp;    edges t;    while(scanf("%d", &n)!=EOF) {        G.clear();        for(int i = 1; i <= n; i++) {            for(int j = 1; j <= n; j++) {                scanf("%d", &tmp);                if(i!=j) {                    t.u = i;                    t.v = j;                    t.w = tmp;                    G.push_back(t);                }            }        }        int res = work();        printf("%d\n", res);    }    return 0;}

0 0
原创粉丝点击