POJ 1251-- template sets the minimum spanning tree problem

Review template
poj 1251

[Title] gives an effect of n points (1 <n <27) of the connected undirected graph, edge side has the right to request a minimum spanning tree for this graph. [Input format comprising a plurality of sets of test data.
Each test line contains an integer number n, representative point, point number capital letters A ~ Z. Next, n - 1
row, side information is given order and connected to each point. Firstly, each line with an uppercase letter, the representative number of the current point (in order); subsequently given an integer k
denotes the number of edges and the point of attachment; write down information on the edges of k sets, each set of information includes a capitalized letter, represents the other side of the connection point, and a positive integer representing the edge weight of the edge (the right side does not exceed
100). When n = 0, stop input. [] Output format for each test case, the output line of the right side represents the minimal spanning tree, and FIG.

For the master template is not enough skilled, we need to engage in active practice

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<vector>
#include<string>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
const int maxn = 30;

int n;
int cnt;
int pre[maxn];

struct node{
    int x,y,val;
}edge[105];

bool cmp(node a,node b){
    return a.val < b.val;
}

void init(){
    for(int i=0; i<27; i++)
        pre[i] = i;
}

int find(int x){
    int r = x;
    while(r!=pre[r])
        r = pre[r];
    while(x!=r){
        int t = pre[x];
        pre[x] = r;
        x = t;
    }
    return r;
}

void join(int a,int b){
    pre[find(a)] = find(b);
}

void input(){
    cnt = 0;
    char a,b;
    int val,t;
    for(int i=0; i<n-1; i++){
        cin >> a >> t;
        while(t--){
            cin >> b >> val;
            edge[cnt].x = a - 'A';
            edge[cnt].y = b - 'A';
            edge[cnt++].val = val;
        }
    }
}
int Kruskal(){
    sort(edge,edge+cnt,cmp);
    int ans = 0;
    int t = 0;
    for(int i=0; i<cnt; i++){
        if(t==n-1)
            break;  //已经连了n-1条线
        if(find(edge[i].x) != find(edge[i].y)){
            ans += edge[i].val;
            join(edge[i].x,edge[i].y);
        }
    }
    return ans;
}

int main(){
    while(cin >> n && n){
        init();
        input();
        cout << Kruskal() << endl;
    }
    return 0;
}

Published 62 original articles · won praise 0 · Views 1737

Guess you like

Origin blog.csdn.net/jhckii/article/details/104577015