TOJ 4117 Happy tree friends

It's a problem of minimum spanning tree,I think it a directed graph that have differences with undirected graph .But it's complete graph.It none of directed business.Use kruskal algorithm to solve this problem.

The portal:http://acm.tju.edu.cn/toj/showp4117.html

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>

using namespace std;

struct Edge{
    int x,y,cap;
};

int bin[105];
Edge edge[10005];
int fee[105][105];
int ans;

int findx(int x){
    if(x != bin[x])
        bin[x] = findx(bin[x]);
    return bin[x];
}

int merge_(int x,int y){
    int fx = findx(x);
    int fy = findx(y);
    if(fx == fy) return 1;
    bin[fy] = fx;
    return 0;
}

int cmp(const void * a1,const void * a2){
    struct Edge p1 = *(struct Edge *)a1;
    struct Edge p2 = *(struct Edge *)a2;
    return p1.cap - p2.cap;
}

void Deal_with(){
    int n;
    while(~scanf("%d",&n)){
        int tempa,cnt = 0;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                scanf("%d",&tempa);
                fee[i][j] = tempa;
                if(i == j)continue;
                edge[cnt].x = i;
                edge[cnt].y = j;
                edge[cnt].cap = tempa;
                cnt ++;
            }
        }
        int u,v;
        scanf("%d %d",&u,&v);
        for(int i=1;i<=100;i++){
            bin[i] = i;
        }
        qsort(edge,cnt,12,cmp);
        merge_(u,v);
        ans = fee[u][v];
        for(int i=0;i<cnt;i++){
            //printf("%d %d %d\n",edge[i].x,edge[i].y,edge[i].cap);
            if(merge_(edge[i].x,edge[i].y)){
                continue;
            }
            else{
                ans += edge[i].cap;
            }
        }
        printf("%d\n",ans);
    }
}

int main(void){
    //freopen("a.in","r",stdin);
    Deal_with();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值