poj 1251 kruskal

简介: http://poj.org/problem?id=1251 #include<algorithm> #include<iostream> #include<cstdlib> #include<cstdio> #include<cmath> using namespace std; #define maxm 205

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

#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
#define maxm 205
#define maxn 30
struct edge
{
    int u,v,w;
} edges[maxm];
int parent[maxn],num,sum;
int N,i,j;
void ufset()
{
    for(i=0; i<maxn; i++)
        parent[i]=-1;
}
int find(int x)
{
    int s;
    for(s=x; parent[s]>=0; s=parent[s]);
    while(s!=x)
    {
        int tmp=parent[x];
        parent[x]=s;
        x=tmp;
    }
    return s;
}
void Union(int R1,int R2)
{
    int r1=find(R1),r2=find(R2);
    int tmp=parent[r1]+parent[r2];
    if(parent[r1]>parent[r2])
    {
        parent[r1]=r2;
        parent[r2]=tmp;
    }
    else
    {
        parent[r2]=r1;
        parent[r1]=tmp;
    }
}
int cmp(const void* a,const void* b)
{
    return ((edge*)a)->w-((edge*)b)->w;
}
int kruskal(int num)
{
    int min = 0;
    int k = 0;
    qsort(edges,num, sizeof(edges[0]), cmp);
    for(int i = 0; i < num; i++)
    {
        if(find(edges[i].v)!= find(edges[i].u))
        {
            Union(edges[i].v,edges[i].u);
            min+=edges[i].w;
            k++;
        }
        if(k == N-1)
            return min;
    }
    return min;
}
int main()
{
    int  r, k, dis;
    char st, en;
  //  freopen("1.txt","r",stdin);
    while(1)
    {
        ufset();
        k= 0;
        cin>>N;
        if(N == 0)
            break;
        for(i = 1; i < N; i++)
        {
            cin>> st >> r;
            for(j = 0; j < r; j++)
            {
                cin>> en >> dis;
                edges[k].u= (int)(st-'A'+1);
                edges[k].v= (int)(en-'A'+1);
                edges[k].w= dis;
                k++;
            }
        }
        cout<< kruskal(k) << endl;
    }
    return 0;
}

  

目录
相关文章
|
人工智能
POJ 3104 Drying
POJ 3104 Drying
|
算法框架/工具
POJ 2262 Goldbach's Conjecture
POJ 2262 Goldbach's Conjecture
145 0
POJ 2027 No Brainer
POJ 2027 No Brainer
116 0
|
算法 数据建模 机器学习/深度学习
F-POJ-3414 Pots
POJ-3414 Time Limit:1000 ms Memory Limit:65536 K Description You are given two po...
1007 0
|
C语言
poj 2503 查字典
Description You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language.
876 0
POJ 2262 Goldbach&#39;s Conjecture
Problem Description In 1742, Christian Goldbach, a German amateur mathematician, sent a letter to Leonhard Euler in which he made the foll...
1017 0
poj 2912 Rochambeau
点击打开链接poj 2912 思路: 带权并查集 分析: 1 有n个小孩玩游戏,里面有一个入是裁判,剩下的人分为三组。现在我们既不知道裁判是谁也不知道分组的情况。
957 0

热门文章

最新文章