zoukankan      html  css  js  c++  java
  • POJ 1251

    题目链接 http://poj.org/problem?id=1251

      本题主要是来求解最小生成树。

      通过并查集来对每一个节点进行存取。(此时节点已经排序根据权值大小)

    以下是代码

     1 #include<iostream>
     2 #include<vector>
     3 #include<algorithm>
     4 #define MAX_N 150
     5 using namespace std;
     6 int pre[MAX_N];
     7 int n;
     8 char c[MAX_N],c1[MAX_N];
     9 int finds(int x)
    10 {
    11     return x==pre[x]?x:finds(pre[x]);
    12 }
    13 void unions(int x, int y)
    14 {
    15     int find_x=finds(x);
    16     int find_y=finds(y);
    17     if(find_x==find_y)
    18         return;
    19     pre[find_x]=find_y;
    20 }
    21 bool Judge(int x, int y)
    22 {
    23     return finds(x)==finds(y);
    24 }
    25 struct Pit
    26 {
    27     int l,r,w;
    28 } p;
    29 vector<Pit> V;
    30 bool cmp(Pit p1,Pit p2)
    31 {
    32     return p1.w<p2.w;
    33 }
    34 int main()
    35 {
    36     while(cin>>n)
    37     {
    38         V.clear();
    39         if(n==0) break;
    40         for(int i=0; i<n; i++)
    41         {
    42             pre[i]=i;
    43         }
    44         for(int i=0; i<n-1; i++)
    45         {
    46             int a;
    47             cin>>c>>a;
    48             for(int i=0; i<a; i++)
    49             {
    50                 int b;
    51                 cin>>c1>>b;
    52                 p.l=c[0]-'A';
    53                 p.r=c1[0]-'A';
    54                 p.w=b;
    55                 V.push_back(p);
    56             }
    57         }
    58         int ans=0;
    59         sort(V.begin(),V.end(),cmp);
    60         for(int i=0; i<V.size(); i++)
    61         {
    62             if(Judge(V[i].l,V[i].r))
    63                 continue;
    64             ans+=V[i].w;
    65             unions(V[i].l,V[i].r);
    66         }
    67         cout<<ans<<endl;
    68     }
    69 
    70 }
  • 相关阅读:
    hdu 1535 Invitation Cards(spfa)
    hdu 1317 XYZZY
    hdu 1245 Saving James Bond
    hdu 1546 Idiomatic Phrases Game
    hdu 1217 Arbitrage(佛洛依德)
    hdu 1599 find the mincost route(无向图的最小环)
    poj1579
    poj1905
    poj1384
    poj3624
  • 原文地址:https://www.cnblogs.com/Yinchen-One/p/8541558.html
Copyright © 2011-2022 走看看