hdu1301 Jungle Roads

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1301
分析:裸的prim

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<bitset>

using namespace std;
int n;
const int INF=1e9;
vector<pair<int,int> > g[30];
int v[30],dis[30]; 
int prim(int n)
{
    memset(v,0,sizeof v);
    for (int i=1;i<=n;i++)  dis[i]=INF;
    dis[1]=0;
    int ans=0;
    for (int i=1;i<=n;i++)
    {
        int mark=-1;
        for (int j=1;j<=n;j++)
          if (!v[j])
          {
                if (mark==-1) mark=j;
                      else  if (dis[j]<dis[mark]) mark=j;
                if (mark==-1) break;
          }
        v[mark]=1;
        ans+=dis[mark];
        for (int j=0;j<g[mark].size();j++)
            if (!v[g[mark][j].first])
            {
                int x=g[mark][j].first;
                dis[x]=min(dis[x],g[mark][j].second);
            }
    }
   return ans;
}           
int main()
{
    while (scanf("%d",&n)==1&&n)
    {
        for (int i=0;i<=n;i++) 
          g[i].clear();
        for (int i=1;i<=n-1;i++)
        {
            char x,xx;
            int k,y;
            scanf("%c",&x);
            scanf("%c %d",&x,&k);

            for (int j=1;j<=k;j++)
            {
                scanf("%c",&xx);
                scanf("%c %d",&xx,&y);  
                g[x-'A'+1].push_back(make_pair(xx-'A'+1,y));
                g[xx-'A'+1].push_back(make_pair(x-'A'+1,y));
            }
        }
        int ans=prim(n);
        printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(hdu1301 Jungle Roads)