Networking

Interview

Time limit1sMemory limit128 MB

Summary
Given points and weighted candidate cable routes, compute the minimum total cable length needed to connect all points (minimum spanning tree).
Level

Easy3 of 10

Topics
Minimum spanning tree, Graph, Union-find
Solved
No attempts yet

Problem

You are asked to design the network connections between certain points in a wide area. You are given a set of points in the area and a set of possible routes for the cables that may connect pairs of points. For each possible route between two points, you are given the length of the cable needed to connect the points along that route. Note that there may be many possible routes between two given points. It is assumed that the given routes connect (directly or indirectly) every two points in the area.

Your task is to design the network so that there is a connection (direct or indirect) between every two points -- that is, all points are interconnected, though not necessarily by a direct cable -- while the total length of the cable used is as small as possible.

Input

The input consists of several data sets, each defining one required network. The first line of a data set contains two integers: the number PP of points, and the number RR of routes between the points. Each of the following RR lines defines one route with three integers: the first two identify the two points, and the third gives the length of the route. The numbers are separated by white space. A data set consisting of a single number P=0P = 0 marks the end of the input. Data sets are separated by an empty line.

The number of points is at most 5050. The maximum length of a route is 100100. The number of possible routes is unlimited. The points are identified by integers from 11 to PP (inclusive). A route between two points ii and jj may be given as i j or as j i.

Output

For each data set, print on its own line a single number: the total length of the cable used for the entire designed network.

Examples1

  1. Example 1

    Input
    1 0
    
    2 3
    1 2 37
    2 1 17
    1 2 68
    
    3 7
    1 2 19
    2 3 11
    3 1 7
    1 3 5
    2 3 89
    3 1 91
    1 2 32
    
    5 7
    1 2 5
    2 3 7
    2 4 8
    4 5 11
    3 5 10
    1 5 6
    4 2 12
    
    0
    
    Expected output
    0
    17
    16
    26