POJ 2075 Tangled in Cables

来源:互联网 发布:阿里云分布式文件系统 编辑:程序博客网 时间:2024/04/30 22:40

Prim+字符串

我偷懒用STL的map了


//============================================================================

// Name        : hello.cpp
// Author      : key
// Version     : 8
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================



#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
#include <map>
using namespace std;

#define NUM_INF 0x7FFFFFFF

bool vis[1010];
double lowc[1010];
double cost[1010][1010];

double prim(int n) // vertex: 0 ~ n-1
{
    int i, j, p;
    double minc, res = 0;
    memset(vis, false, sizeof(vis));
    vis[0] = true;
    for (i=1; i<n; i++)
        lowc[i] = cost[0][i];

    for (i=1; i<n; i++)
    {
        minc = NUM_INF; p = -1;
        for (j=0; j<n; j++)
        {
            if (false == vis[j] && minc > lowc[j])
            {
                minc = lowc[j];
                p = j;
            }
        }
        
        if (NUM_INF == minc)
            return -1; // 原图不连通
            
        res += minc;
        vis[p] = true;
        for (j=0; j<n; j++)
        {
            if (false == vis[j] && lowc[j] > cost[p][j])
            {
                lowc[j] = cost[p][j];
            }
        }
    }
    return res;
}

map<string,int> m;

int main()
{
    int n;
    int i,j;
    double max_ans;
    int t;
    char str[110];
    char str1[110],str2[110];
    double w;
    while(scanf("%lf%d",&max_ans,&n)!=EOF)
    {
        for(i=0;i<n;i++)
        {
            scanf("%s",str);
            m[str] = i;
        }
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                cost[i][j] = NUM_INF;
            }
        }
        scanf("%d",&t);
        while(t--)
        {
            scanf("%s %s %lf",str1,str2,&w);
            i = m[str1];
            j = m[str2];
            if(cost[i][j] > w)
            {
                cost[i][j] = cost[j][i] = w;
            }
        }
        w = prim(n);
        if(w <= max_ans)
            printf("Need %.1f miles of cable\n",w);
        else
            printf("Not enough cable\n");
    }
    return 0;
}