LightOJ - ???? 最短修復路線(最小生成樹)

Description

There are several cities in the country, and some of them are connected by bidirectional roads. Unfortunately, some of the roads are damaged and cannot be used right now. Your goal is to rebuild enough of the damaged roads that there is a functional path between every pair of cities.

You are given the description of roads. Damaged roads are formatted as "city1 city2 cost" and non-damaged roads are formatted as "city1 city2 0". In this notation city1 and city2 are the case-sensitive names of the two cities directly connected by that road. If the road is damaged, cost represents the price of rebuilding that road. Every city in the country will appear at least once in roads. And there can be multiple roads between same pair of cities.

Your task is to find the minimum cost of the roads that must be rebuilt to achieve your goal. If it is impossible to do so, print "Impossible".

Input

Input starts with an integer T (≤ 50), denoting the number of test cases.

Each case begins with a blank line and an integer m (1 ≤ m ≤ 50) denoting the number of roads. Then there will be m lines, each containing the description of a road. No names will contain more than 50 characters. The road costs will lie in the range [0, 1000].

Output

For each case of input you have to print the case number and the desired result.

Sample Input

2

 

12

Dhaka Sylhet 0

Ctg Dhaka 0

Sylhet Chandpur 9

Ctg Barisal 9

Ctg Rajshahi 9

Dhaka Sylhet 9

Ctg Rajshahi 3

Sylhet Chandpur 5

Khulna Rangpur 7

Chandpur Rangpur 7

Dhaka Rajshahi 6

Dhaka Rajshahi 7

 

2

Rajshahi Khulna 4

Kushtia Bhola 1

Sample Output

Case 1: 31

Case 2: Impossible


題解,簡單的最小生成樹,用map保存字符串的結點,用於並查集。


#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
const int max_m = 60;
map<string,string> p;
int m,len;
string u1,v1;
int c;

struct node{
    string u,v;
    int cost;
}pic[max_m];

bool cmp(const node& n1,const node& n2){
    return n1.cost < n2.cost;
}

string find_(string x){  //並查集
    return p[x] == x ? x : p[x] = find_(p[x]);
}
void MST(){
    int ans = 0;
    unsigned int l = 0;
    sort(pic,pic+len,cmp);
    for(int i = 0; i < len; i++){
        string x1 = find_(pic[i].u);
        string x2 = find_(pic[i].v);
        if(x1!=x2){
            p[x1] = x2;
            ans+=pic[i].cost;
            l++;
        }
    }
    l != p.size()-1?cout<<"Impossible"<<endl : cout<<ans<<endl;
    p.clear();
}

int main(){
    int T;
    cin>>T;
    for(int i = 1; i <= T; i++){
        cin>>m;len = 0;
        for(int j = 0 ; j < m; j++){
            cin>>u1>>v1>>c;
            p[u1] = u1;
            p[v1] = v1;
            pic[len].u = u1; //記錄結點
            pic[len].v = v1;
            pic[len].cost = c;
            len++;
        }
        cout<<"Case "<<i<<": ";
        MST();
    }
    return 0;
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章