POJ1258 Kruscal

来源:互联网 发布:mac爱奇艺弹幕 编辑:程序博客网 时间:2024/05/21 14:00

2017年4月4日 | ljfcnyali
Kruscal水过,直接给代码!
Sample Input

40 4 9 214 0 8 179 8 0 1621 17 16 0

Sample Output

28
/*************************************************************************    > File Name: POJ1258.cpp    > Author: ljf-cnyali    > Mail: ljfcnyali@gmail.com     > Created Time: 2017/4/4 14:48:23 ************************************************************************/#include<iostream>#include<cstdio>#include<cstdlib>#include<cmath>#include<cstring>#include<algorithm>#include<map>#include<set>#include<vector>#include<queue>using namespace std;#define REP(i, a, b) for(int i = (a), _end_ = (b);i <= _end_; ++ i)#define mem(a) memset((a), 0, sizeof(a))#define str(a) strlen(a)const int maxn = 550;int n, m;struct node {    int x, y, w;}Edge[maxn * maxn];int fa[maxn];int cmp(node x, node y) {    return x.w < y.w;}int cha(int x) {    return x == fa[x] ? x : fa[x] = cha(fa[x]);}int main() {#ifndef ONLINE_JUDGE    freopen("input.txt", "r", stdin);    freopen("output.txt", "w", stdout);#endif    while(~scanf("%d", &m)) {        int w;        n = 0;        REP(i, 1, m) {            fa[i] = i;            REP(j, 1, m)                if(scanf("%d", &w) && i < j) {                    Edge[++ n].x = i;                    Edge[n].y = j;                    Edge[n].w = w;                }        }        sort(Edge + 1, Edge + n + 1, cmp);        int ans = 0, sum = 0;        REP(i, 1, n) {            int fx = cha(Edge[i].x);            int fy = cha(Edge[i].y);            if(fx != fy) {                fa[fx] = fy;                ans += Edge[i].w;                if(++ sum == m - 1)                    break ;            }        }        printf("%d\n", ans);    }    return 0;}

本文转自:http://ljf-cnyali.cn/index.php/archives/133

原创粉丝点击