关闭

TOJ 4117 Happy tree friends

标签: TOJacmKraskal
214人阅读 评论(0) 收藏 举报

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;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:59280次
    • 积分:3591
    • 等级:
    • 排名:第9127名
    • 原创:315篇
    • 转载:3篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论