HDU-1863- expedite project (disjoint-set + Kruskal)

Smooth Traffic Project

Problem Description

Target provincial government "Smooth Traffic Project" is to make between any two villages in the province can achieve road traffic (but not necessarily directly connected to the road, as long as indirectly through the road up to). After investigation and assessment, statistics obtained a list of possible construction of several roads highway costs. Now you write a program to calculate the lowest cost needed to clear the province.

Input

Test input contains several test cases. The first row of each road test strip evaluation given number N, the number of villages M (<100); N subsequent
cost of correspondence between the village road rows each given a pair of positive integers, respectively, two villages the number and cost of road between these two villages (and a positive integer). For simplicity, the village numbered from 1 to M. When N is 0, all the input end, an output not corresponding results.

Output

For each test case, output the lowest cost needed to clear the province in a row. If the data is not sufficient to ensure the smooth flow statistics, output "?."

Sample Input

3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100
 

Sample Output

3
?

Problem-solving ideas:

kruskul minimum spanning tree calculation. Disjoint-set recording connectivity.

AC Code:

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5+10;
int par[N];

struct node{
    int to,from;
    int w;
}edges[N];
int cnt,n;

bool cmp(node a1,node a2)
{
    return a1.w<a2.w;
}
int find_(int x)
{
    return par[x] == x ? x : find_(par[x]);
}
void union_(int a,int b)
{
    par[find_(a)] = par[find_(b)];
}
int same(int a,int b)
{
    return find_(a) == find_(b);
}
int kruskal()
{
    int res  = 0;
    sort(edges,edges+n,cmp);
    for(int i = 0 ; i < n ; i ++)
    {
        if(!same(edges[i].to,edges[i].from))
        {
            union_(edges[i].to,edges[i].from);
            res += edges[i].w;
        }
    }
    return res;
}

signed main()
{
    int m;
    while(~scanf("%lld%lld",&n,&m) &&  n)
    {
        for(int i = 0 ; i < n ; i ++)
        {
            int a,b,c;
            scanf("%lld%lld%lld",&a,&b,&c);
            edges[i].to = a;
            edges[i].from = b;
            edges[i].w = c;
        }
        for(int i = 0 ; i <= m ; i ++)
            par[i] = i;
        int ans = kruskal();
        int cnt = 0;
        for(int i = 1 ; i <= m ; i ++)
        {
            if(par[i] == i)
                cnt++;
        }
        if(cnt != 1)
            cout<<"?"<<endl;
        else
            cout<<ans<<endl;
    }
}

Published 104 original articles · won praise 7 · views 4075

Guess you like

Origin blog.csdn.net/qq_43461168/article/details/103429798