poj1287 kruskal

简介: http://poj.org/problem?id=1287 #include<cstdio> #include<cstdlib> #include<iostream> #define N 60 using namespace std; struct node { int x,y; int len; } city[26

http://poj.org/problem?id=1287

#include<cstdio>
#include<cstdlib>
#include<iostream>
#define N 60
using namespace std;
struct node
{
    int x,y;
    int len;
} city[2600];
typedef struct node NODE;
int n,m,pre[N];
int cmp(const void *a,const void *b)
{
    return ((NODE*)a)->len - ((NODE*)b)->len;
}
int find( int x )
{
    while( x!= pre[x] )
        x = pre[x];
    return x;
}
void kruskal()
{
    int i,a,b,sum = 0;
    qsort(city,m,sizeof(NODE),cmp);
    for(i=1; i<=n; i++)
        pre[i] = i;
    for(i=0; i<m; i++)
    {
        a = find(city[i].x);
        b = find(city[i].y);
        if( a!= b)
        {
            sum += city[i].len;
            pre[b] = a;
        }
    }
    cout << sum << endl;
}
int main()
{
    //freopen("3.txt","r",stdin);
    while( cin>>n && n )
    {
        cin>>m;
        for(int i=0; i<m; i++)
            cin >> city[i].x >> city[i].y >> city[i].len;
        kruskal();
    }
    return 0;
}

  

目录
相关文章
|
4天前
Hopscotch(POJ-3050)
Hopscotch(POJ-3050)
POJ 2487 Stamps
POJ 2487 Stamps
84 0
|
人工智能 BI
|
机器学习/深度学习 算法
|
机器学习/深度学习
|
算法 计算机视觉
最小割-poj-2914
poj-2914-Minimum Cut Description Given an undirected graph, in which two vertices can be connected by multiple edges, what is the size of the minimum cut of the graph? i.e. how many edges must b
1532 0