zoukankan      html  css  js  c++  java
  • POJ1251-Jungle Roads

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

    分析:kruskal算法。因为节点是字符,所以开map做并查集,效果同数组。

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>
     4 #include <map>
     5 using namespace std;
     6 map<char,char>f;
     7 char u,v;
     8 int n,k,w,cnt,tot,ans;
     9 struct edge
    10 {
    11     char u,v;
    12     int w;
    13 }e[1100];
    14 char find(char k)
    15 {
    16     if(f[k]==k)return k;
    17     return f[k]=find(f[k]);
    18 }
    19 int cmp(edge a,edge b)
    20 {
    21     return a.w<b.w;
    22 }
    23 void add(char u,char v,int w)
    24 {
    25     e[++cnt].u=u;
    26     e[cnt].v=v;
    27     e[cnt].w=w;
    28 }
    29 int main(void)
    30 {
    31     while(cin>>n&&n)
    32     {
    33         ans=tot=cnt=0;
    34         for(int i=1;i<=n-1;i++)
    35         {
    36             cin>>u>>k;
    37             f[u]=u;
    38             for(int i=1;i<=k;i++)
    39             {
    40                 cin>>v>>w;
    41                 f[v]=v;
    42                 add(u,v,w);
    43             }
    44         }
    45         sort(e+1,e+1+cnt,cmp);
    46         for(int i=1;i<=cnt;i++)
    47         {
    48             char fu=find(e[i].u),fv=find(e[i].v);
    49             if(fu==fv)continue;
    50             f[fu]=fv;
    51             ans+=e[i].w;
    52             if(++tot==n-1)break;
    53         }
    54         cout<<ans<<endl;
    55     }
    56     return 0;
    57 }
  • 相关阅读:
    zoj1589Professor John
    zoj1082Stockbroker Grapevine
    zoj1311Network
    zoj1060Sorting It All Out
    zoj1119SPF
    zju1085Alien Security
    zoj 2474Benny's Compiler
    zoj1068P,MTHBGWB
    what's next?
    ski for the first time~
  • 原文地址:https://www.cnblogs.com/yanying7/p/12691556.html
Copyright © 2011-2022 走看看