POJ 2421 Constructing Roads (Kruskal algorithm + compression path and check set)

Source: Internet
Author: User

Constructing Roads
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 19884 Accepted: 8315

Description

There is N villages, which is numbered from 1 to N, and we should build some roads such that every both villages can con Nect to all other. We say village A and B are connected, if and only if there is a road between A and B, or there exists a village C such That there was a road between A and C, and C and B are connected.

We know that there be already some roads between some villages and your job is the build some roads such so all the Vil Lages is connect and the length of the roads built is minimum.

Input

The first line is a integer n (3 <= N <=), which is the number of villages. Then come n lines, the i-th of which contains n integers, and the j-th of these n integers are the distance (the distance s Hould is an integer within [1, +]) between village I and village J.

Then there was an integer q (0 <= q <= n * (n + 1)/2). Then come Q lines, each line contains the integers a and B (1 <= a < b <= N), which means the road between Villag e A and village B has been built.

Output

You should output a line contains an integer, which is the length of the "All" the roads to being built such that all the villages is connected, and this value is minimum.

Sample Input

30 990 692990 0 179692 179 011 2

Sample Output

179
Topic Analysis:
Enter n villages, and then enter an adjacency matrix to indicate the distance to point to points, and then enter the M edge, indicating that the M-bar is connected, regardless of the path length, if you want to connect all the points
How long does it need to be repaired as soon as possible?
Algorithm Analysis: This topic and the standard template is different, the title input is a two-dimensional adjacency matrix value, and then the input m bar has been connected to the edge, that is, these edges have been well connected, these
Side length don't calculate it. using the Kruskal algorithm, and checking the set not only to initialize, but also to the related processing of these edges, to establish a parent-child relationship.
Code:

#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm>using namespace    std;struct node{int u;    int V;    int W;       the BOOL operator < (const node&x) const//node class has its own operator overloads, so that when you sort, you can write directly, without calling the function {return w<x.w;    }}q[5000];int fa[105];int findset (int x) {return fa[x]!=x?fa[x]=findset (Fa[x]): x;}//With compressed path and set int main () {int n, m;    int u, v;    int I, J;    int DD;    int e=0;    scanf ("%d", &n); for (I=1; i<=n; i++) {for (j=1; j<=n; J + +) {scanf ("%d", &dd),//Because it is a no-map, so it only needs to store an upper triangle            Data or the next triangle of data on the line, I store the upper triangle if (i<j) {q[e].u=i; q[e].v =j; q[e++].w=dd;//record into the structure }}}//Sort (q+0, q+e);  The structure array is sorted, the edge weights are sorted by the front sort for (i=0; i<=n; i++) {fa[i]=i;  and check the array initialization, the initial point to themselves} scanf ("%d", &m);         Read in M-bar while (m--) {scanf ("%d%d", &u, &v); Fa[findset (u)] = Findset (v); indicates that u and V have beenAfter having the same path does not need to build the road, so on the coffee table and put them into a subset} int ans=0; Used to record the total length of the path to be built for (int k=0; k<e; k++) {if (Findset (q[k].u)!=findset (Q[K].V))//If the structure element stores two villages that do not belong to the same        subcollections {fa[fa[q[k].u]] = FA[Q[K].V];//merge the village into a subset or merge it into a tree ans+=q[k].w;  }} printf ("%d\n", ans); This code can also be optimized in time, that is, starting from the input m bar to count the number of edges that have been added to the spanning tree, to define a count variable, when the value of the count variable ==n-1 can jump out of the loop above
return 0;}

This is from the "Data structure programming experiment," the book Read the code: Written in Java, feel and check set with a good, but in the search for the edge of the three-layer loop is not very good, time performance is too poor, and there is no need to cycle

It is better to rewrite the array into a struct.

The code is as follows:

Import Java.util.*;import java.io.reader;import java.io.writer;import java.math.*; The toolkit under Import Java public class Main{public static void print (String x) {//output minimum spanning tree Bingchang System.out.print (x);} Static int[] FA; and check the array public static int findset (int x) {return fa[x]!=x?fa[x]=findset (Fa[x]): x;}//with a compressed path and check set public static void Main ( String[] argv) {//The parameter defining the main function is an array of type string argvscanner input = new Scanner (system.in);//define Java's standard input while ( Input.hasnextint ()) {//multi-group Test int N = Input.nextint (); int [][]p = new int [n+1][n+1];//request memory for (int i=0; i<n; i++) for adjacency matrix {f or (int j=0; j<n; J + +) {P[i][j] = Input.nextint ();}} FA = new Int[n+1];  Apply memory for (int i=0; i<n; i++) fa[i]=i for the array of the and check sets; The parent node pointer points to itself initialize for (int m=intput.nextint (); m>0; m--) {Fa[findset (Input.nextint ()-1)] = Findset (Input.nextint ()-1); Establish parent-child relationship}int Ans=0; The length of the new road is initialized for (int k=1, k<=1000; k++) {for (Int. i=0; i<n; i++) {for (int j=0; j<n; J + +) {if (P[i][j]==k && fi Ndset (i)!=findset (j)) {Fa[fa[i]] = Fa[j];ans+=k;}}} Print (ans+ "\ n");}}}

POJ 2421 Constructing Roads (Kruskal algorithm + compression path and check set)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.