Tangled in Cables(Kruskal+map容器处理字符串)

/**
题意:
    给你两个城市之间的道路(无向图),求出需要的
    电缆。如果大于所提供的,就输出Not enough 。。。
    否则输出所需要的电缆长度。
 
    输入:N (给定的电缆总长度)
          m1 (有多少个城市—)
          str1
          str2
          str3
          str4
          :
          ;(城市的名字)
 
          m2(相当于给出m2条边)
          a  b  c (a城市到b城市的距离为c)
          :
          :
          :
          :
    输出:
         所需的最短长度   若大于给定的长度  输出 Not enough cable
 
分析: 简单的最小生成树+字符串处理
        用map容器映射处理简单
 
 
*/
 
 
#include<stdio.h>
#include<map>
#include<algorithm>
#include<string>
#include<string.h>
#include<iostream>
using namespace std;
const int MAX=1e4;///1*10 的4次方
int vest[MAX];
int n,m;
double leng=0;
map<string,int >mp;
struct node
{
    int u,v;
    double w;
} bian[MAX];
bool  cmp(node a,node b)
{
    return a.w<b.w;
}
void init(int n)
{
    for(int i=0; i<=n; i++)
        vest[i]=i;
}
int Find(int t)
{
        if(vest[t]==t)return t;
     return  Find(vest[t]);
 
}
bool merge(int a,int b)
{
    int x=Find(a);
    int y=Find(b);
    if(x!=y)
    {
        vest[x]=y;
        return true;
    }
    return false;
}
double Kruskal()
{
    double sum=0;
    int cnt=0;
    for(int i=0; i<m; i++)
    {
        if(merge(bian[i].u,bian[i].v))
        {
            sum+=bian[i].w;
            ++cnt;
        }
        if(cnt>=n-1)break;
    }
    return sum;
}
int main()
{
    scanf("%lf",&leng);
    {
 
        mp.clear();
        scanf("%d",&n);
        init(n);
        char a[25];
        int k=1;
        for(int i=0; i<n; i++)
        {
            scanf("%s",a);
            if(mp[a]==0)mp[a]=k++;///给第一次出现的城市编号
        }
        scanf("%d",&m);
        char b[25];
        double c;
        for(int i=0; i<m; i++)
        {
            scanf("%s%s%lf",a,b,&c);
            bian[i].u=mp[a];
            bian[i].v=mp[b];
            bian[i].w=c;
        }
        sort(bian,bian+m,cmp);
        double sum=Kruskal();
        if(sum>=leng)printf("Not enough cable ");
        else printf("Need %.1lf miles of cable ",sum);
    }
    return 0;
}
梦里不知身是客,一晌贪欢。
原文地址:https://www.cnblogs.com/dccmmtop/p/5546581.html