Agri-Net(sdut_1262)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
struct node
{
    int u;
    int v;
    int w;
}q[11234];
int a[110];
int d[110][110];
bool cmp(struct node a, struct node b)
{
    return a.w < b.w;
}
int f(int x)
{
    while(x != a[x]){
        x = a[x];
    }
    return x;
}
int mer(int x, int y)
{
    int f1, f2;
    f1 = f(x);
    f2 = f(y);
    if(f1 != f2){
        a[f1] = f2;
        return 1;
    }else {
        return 0;
    }
}
int main()
{
    int n;
    int cnt;
    while(~scanf("%d", &n)){
        int i, j;
        for(i  =1;i <= n;i++){
            a[i] = i;
        }
        for(i = 1;i <= n;i++){
            for(j = 1;j <= n;j++){
                scanf("%d", &d[i][j]);
            }
        }
        cnt = 0;
        for(i  =1;i <= n;i++){
            for(j =i+1;j <= n;j++){
                q[cnt].u = i;
                q[cnt].v = j;
                q[cnt].w= d[i][j];
                cnt++;
            }
        }
        sort(q,q+cnt,cmp);
        int sum = 0;
        int cou = 0;
        for( i =0;i < cnt;i++){
            if(mer(q[i].u,q[i].v)){
                sum += q[i].w;
                cou++;
            }
            if(cou == n-1){
                break;
            }
        }
        printf("%d\n", sum);
    }

    return 0;
}

你可能感兴趣的:(Agri-Net(sdut_1262))