Hangzhou Electric OJ1232 Smooth Project Java Implementation and Collection

Recently, I learned the merge search algorithm while reading "Algorithm Fourth Edition", and consolidate my knowledge through a question. I also hope that I can help the people who write this question.
Topic link

Title description

Problem Description

A province investigates the urban traffic conditions and obtains a statistical table of existing urban roads, which lists the cities and towns directly connected to each road. The goal of the Provincial Government's "Unblocked Project" is to enable traffic between any two towns in the province (but not necessarily directly connected by roads, as long as they are reachable through roads indirectly). Ask at least how many roads need to be built?
Input
test input contains several test cases. The first line of each test case gives two positive integers, which are the number of towns N (<1000) and the number of roads M; the subsequent M lines correspond to M roads, and each line gives a pair of positive integers, respectively The number of two towns directly connected by a road. For simplicity, the towns are numbered from 1 to N.
Note: There can be multiple roads between the two cities, which means that the input of
3 3
1 2
1 2
2 1
is also legal.
When N is 0, the input ends and the use case is not processed.
Output
For each test case, output the minimum number of roads that need to be built in one line.
Sample Input
4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
Sample Output
1
0
2
998

Code

import java.util.Scanner;

public class Main {
    
    
    static int[] id;
    static int[] sz;

    static int find(int a) {
    
    
        return a == id[a] ? a : find(id[a]);
    }

    static void union(int a, int b) {
    
    
        if (a == b) return;
        int x = find(a), y = find(b);
        if (sz[x] >= sz[y]) {
    
    
            id[y] = x;
            sz[x] += sz[y];
        } else {
    
    
            id[x] = y;
            sz[y] += sz[x];
        }
    }

    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
    
    
            int N = sc.nextInt();
            if (N == 0) break;
            int M = sc.nextInt();
            id = new int[N + 1];
            sz = new int[N + 1];
            for (int i = 0; i < id.length; i++) {
    
    
                id[i] = i;
                sz[i] = 1;
            }
            for (int i = 0; i < M; i++) {
    
    
                int x = sc.nextInt(), y = sc.nextInt();
                union(x, y);
            }

            int count=0;
            for (int i = 1; i <id.length; i++) {
    
    
                if(i==id[i])count++;
            }
            System.out.println(count-1);
        }

    }

}

Guess you like

Origin blog.csdn.net/ln82799/article/details/109191724