๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 1976_์—ฌํ–‰ ๊ฐ€์ž

๋ฟŒ์•ผ._. 2023. 9. 1. 12:10

Gold IV

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/1976)

< ์—ฌํ–‰ ๊ฐ€์ž >

 

๋ฌธ์ œ ํ’€์ด 

 

Union-Find ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ†ตํ•ด ๊ฐ™์€ ์ง‘ํ•ฉ์ธ์ง€ ํ™•์ธํ•ด์„œ ์—ฌํ–‰์˜ ๊ฐ€๋Šฅ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ–ˆ๋‹ค.

 

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class _1976_ { // ์—ฌํ–‰ ๊ฐ€์ž
	static int arr[];

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;

		int n = Integer.parseInt(bf.readLine());
		int m = Integer.parseInt(bf.readLine());

		arr = new int[n + 1];
		for(int i=0; i<n+1; i++) {
			arr[i]=i;
		}

		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(bf.readLine());

			for (int j = 0; j < n; j++) {
				int x = Integer.parseInt(st.nextToken());
				if (x == 1) {
					int a = find(i + 1);
					int b = find(j + 1);

					if (a > b)
						arr[a] = b;
					else
						arr[b] = a;
				}
			}
		}

		st = new StringTokenizer(bf.readLine());
		int result = find(Integer.parseInt(st.nextToken()));
		boolean flag = false;

		for (int i = 1; i < m; i++) {
			int num = find(Integer.parseInt(st.nextToken()));
			if (result != num) {
				flag = true;
				break;
			}
		}

		if (!flag) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}
	}

	private static int find(int i) {
		if (arr[i] == i)
			return i;
		return arr[i] = find(arr[i]);
	}

}

 

Main

๋ณ€์ˆ˜)
n : ๋„์‹œ์˜ ์ˆ˜
m : ์—ฌํ–‰ ๊ณ„ํš์— ์†ํ•œ ๋„์‹œ์˜ ์ˆ˜
arr : ์ง‘ํ•ฉ
result : ์—ฌํ–‰ ๊ณ„ํš์— ์†ํ•œ ์ฒซ ๋ฒˆ์งธ ๋„์‹œ์˜ ์ง‘ํ•ฉ ๋ฒˆํ˜ธ 
flag : ๊ฐ€๋Šฅ ์—ฌ๋ถ€

 

- ๋„์‹œ์˜ ์ˆ˜(n), ์—ฌํ–‰ ๊ณ„ํš์— ์†ํ•œ ๋„์‹œ์˜ ์ˆ˜(m) ์ž…๋ ฅ

- ์ง‘ํ•ฉ์„ ๊ตฌ๋ถ„ํ•˜๊ธฐ ์œ„ํ•ด ๋ฐฐ์—ด์„ index ๋ฒˆํ˜ธ์™€ ๋™์ผํ•˜๊ฒŒ ์ดˆ๊ธฐํ™”

- ๋„์‹œ์˜ ์—ฐ๊ฒฐ ์ •๋ณด ์ž…๋ ฅ

: 1์ด๋ฉด ์—ฐ๊ฒฐ๋œ ๊ฒƒ์ด๋ฏ€๋กœ ๊ฐ™์€ ์ง‘ํ•ฉ์ž„์„ ํ‘œ์‹œ

- ์—ฌํ–‰ ๊ณ„ํš์— ์†ํ•œ ๋„์‹œ ์ค‘์—์„œ ์ฒซ ๋ฒˆ์งธ ๋„์‹œ์˜ ์ง‘ํ•ฉ์„(result) ๋จผ์ € ๊ตฌํ•จ

- ์—ฌํ–‰ ๊ณ„ํš์— ์†ํ•œ ๋„์‹œ ํƒ์ƒ‰

: ์œ„์—์„œ ๊ตฌํ•œ ์ง‘ํ•ฉ๊ณผ ๋‚˜๋จธ์ง€ ์—ฌํ–‰ ๊ณ„ํš์— ์†ํ•œ ๋„์‹œ์˜ ์ง‘ํ•ฉ์ด ๋‹ค๋ฅด๋ฉด ๋ถˆ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ ์ค‘์ง€

- flag ์—ฌ๋ถ€์— ๋”ฐ๋ผ ์ •๋‹ต ์ถœ๋ ฅ

 

find

- arr[i]์™€ i๊ฐ€ ๊ฐ™๋‹ค๋ฉด ๋ถ€๋ชจ ๋…ธ๋“œ ์ด๋ฏ€๋กœ i ๋ฐ˜ํ™˜

- arr[i]์™€ i๊ฐ€ ๊ฐ™์ง€ ์•Š๋‹ค๋ฉด ๋ถ€๋ชจ ๋…ธ๋“œ๊ฐ€ ์•„๋‹ˆ๋ฏ€๋กœ ๋‹ค์‹œ find๋ฅผ ํ˜ธ์ถœํ•˜๋ฉฐ ๋‚˜์ค‘์— ๊ฐ™์€ ์ผ์„ ๋ฐ˜๋ณตํ•˜์ง€ ์•Š๋„๋ก ๊ฐ’ update