Prim_poj2075 Tangled in Cables

題意:最小生成樹問題,加上簡單的字符串處理

/*
Sample Input

100.0
4
Jones
Smiths
Howards
Wangs
5
Jones Smiths 2.0
Jones Howards 4.2
Jones Wangs 6.7
Howards Wangs 4.0
Smiths Wangs 10.0
Sample Output

Need 10.2 miles of cable

*/
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<iostream>

#define MAXN 250
#define INF 1000000000

using namespace std;

map<string, int>  bianhao;

double Gmap[MAXN][MAXN];
double LowValue[MAXN];
bool visited[MAXN];

double Prim(int n){
    memset(visited, 0, sizeof(visited));
    visited[0] = 1;
    for(int i = 0; i < n; i++){
        LowValue[i] = Gmap[0][i];
    }
    int st;
    double sum = 0;
    for(int i = 1; i < n; i++){
        double minV = INF;
        for(int j = 0; j < n; j++){
            if(!visited[j] && LowValue[j] < minV){
                minV = LowValue[j];
                st = j;
            }
        }
        visited[st] = 1;sum += minV;
        for(int j = 0; j < n; j++){
            if(!visited[j] && Gmap[st][j] < LowValue[j]) LowValue[j] = Gmap[st][j];
        }
    }
    return sum;
}
void inint(int n){
    for(int i = 0; i< n + 10;i++){
        for(int j = 0; j < n +10; j++){
            Gmap[i][j] = INF;
        }
    }
}
int main(){
    double calen;
    int n, m;
    string str,str1, str2;
    double l;
    while(cin>>calen){
        cin>>n;
        inint(n);
        bianhao.clear();
        for(int i = 0; i < n; i++){
            cin>>str;
            bianhao[str] = i;
        }
        cin>>m;
        for(int i = 0; i < m; i++){
            cin>>str1>>str2>>l;
            Gmap[bianhao[str1]][bianhao[str2]] = Gmap[bianhao[str2]][bianhao[str1]] = l;
        }
        double len = Prim(n);
        if(calen - len >= 0.0000000001)  printf("Need %.1f miles of cable\n", len);
        else printf("Not enough cable\n");
    }
}


發佈了100 篇原創文章 · 獲贊 8 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章