hoj1751

/*This Code is Submitted by billforum for Problem 1751 at 2012-02-15 12:44:59*/
#include <iostream>
#include <stdio.h>
#include <map>
#include <cmath>
#include <algorithm>
using namespace std;

const int N=600;
const double Max=20000;
int n;
double a[N],d[N][N],total;
bool f[N];


void path()
{
    int k;
    f[1]=1;
    k=1;
    total=0;
    for(int i=2;i<=n;i++)
    {
        double mcost=Max;
        for(int j=2;j<=n;j++)
        {
            if(!f[j]&&(a[j]<mcost))
            {
                mcost=a[j];
                k=j;
            }
        }
        f[k]=1;
        total+=a[k];
        for(int t=2;t<=n;t++)
        {
            if(!f[t]&&(d[k][t]<a[t]))
            a[t]=d[k][t];
        }
    }
    return;
}

int main()
{
    double cable,c;
    int m;
    string tmp,t1,t2;
    map<string,int> name;
    map<string,int>::iterator iter;
   while(cin>>cable)
   {
      cin>>n;
      for(int i=1;i<=n;i++)
      {
          f[i]=0;
          for(int j=i+1;j<=n;j++)
          {
              d[i][j]=Max;
              d[j][i]=Max;
          }
      }
      for(int i=1;i<=n;i++)
      {
          cin>>tmp;
          name.insert(pair<string,int>(tmp,i));
      }
     //for(iter=name.begin();iter!=name.end();iter++)
      //cout<<iter->first<<"    "<<iter->second<<endl;
      cin>>m;
      for(int i=1;i<=m;i++)
      {
          int f,s;
         cin>>t1>>t2>>c;
         f=name.find(t1)->second;
         s=name.find(t2)->second;
         d[f][s]=c;
         d[s][f]=c;
      }
      for(int i=2;i<=n;i++)
      a[i]=d[1][i];
      a[1]=0;
      path();
     if(total>cable) cout<<"Not enough cable"<<endl;
     else printf("Need %.1lf miles of cable\n",total);
      //cout<<a[s]<<endl;
   }
    return 0;
}

 

posted @ 2012-02-15 12:48  wuzhibin  阅读(151)  评论(0)    收藏  举报