๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 24484_์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜์—… - ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ 6

๋ฟŒ์•ผ._. 2023. 6. 7. 13:51

Silver II

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

< ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜์—… - ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ 6 >

 

๋ฌธ์ œ ํ’€์ด

 

dfs๋กœ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ๋…ธ๋“œ์˜ ๊นŠ์ด์™€ ๋…ธ๋“œ์˜ ๋ฐฉ๋ฌธ ์ˆœ์„œ๋ฅผ ์ €์žฅํ•ด ์ค€๋‹ค.

 

 

 

 my solution (Java)

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

public class _24484_ { // ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜์—… - ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ 6 
	static ArrayList<ArrayList<Integer>> arr;
	static long d[], t[];
	static int index;

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

		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());
		int r = Integer.parseInt(st.nextToken()) - 1;

		arr = new ArrayList<>();
		d = new long[n];
		t = new long[n];
		for (int i = 0; i < n; i++) {
			arr.add(new ArrayList<>());
			d[i] = -1;
		}

		for (int i = 0; i < m; i++) {
			st = new StringTokenizer(bf.readLine());
			int u = Integer.parseInt(st.nextToken()) - 1;
			int v = Integer.parseInt(st.nextToken()) - 1;
			arr.get(u).add(v);
			arr.get(v).add(u);
		}

		for (int i = 0; i < n; i++) {
			Collections.sort(arr.get(i), Collections.reverseOrder());
		}

		d[r] = 0;
		t[r] = 1;
		index = 2;
		dfs(r);

		long result = 0;
		for (int i = 0; i < n; i++) {
			result += d[i] * t[i];
		}
		System.out.println(result);
	}

	private static void dfs(int r) {
		for (int i = 0; i < arr.get(r).size(); i++) {
			if (d[arr.get(r).get(i)] == -1) {
				d[arr.get(r).get(i)] = d[r] + 1;
				t[arr.get(r).get(i)] = index++;
				dfs(arr.get(r).get(i));
			}
		}
	}
}

 

Main

- ์ •์ ์˜ ์ˆ˜ (n), ๊ฐ„์„ ์˜ ์ˆ˜ (m), ์‹œ์ž‘ ์ •์  (r) ์ž…๋ ฅ

- arr : ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ

   d : ๋…ธ๋“œ์˜ ๊นŠ์ด (๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด -1๋กœ ์ดˆ๊ธฐํ™”)

   t : ๋…ธ๋“œ์˜ ๋ฐฉ๋ฌธ ์ˆœ์„œ

- ์–‘๋ฐฉํ–ฅ์œผ๋กœ ๊ทธ๋ž˜ํ”„ ์ €์žฅ ๋ฐ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ

- ์‹œ์ž‘ ์ •์ ์˜ ๋…ธ๋“œ์˜ ๊นŠ์ด๋Š” 0, ๋…ธ๋“œ์˜ ๋ฐฉ๋ฌธ ์ˆœ์„œ๋Š” 1๋กœ ์ดˆ๊ธฐํ™” ํ›„ dfs ํ•จ์ˆ˜ ํ˜ธ์ถœ

-  result: d x t ํ•ฉ

 

dfs(์‹œ์ž‘ ์ •์  r)

- ์‹œ์ž‘ ์ •์ ์˜ ์ธ์ ‘ ์ •์ ์˜ ์ˆ˜๋งŒํผ ๋ฐ˜๋ณตํ•˜์—ฌ ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ์ธ์ง€ ํ™•์ธ (๋…ธ๋“œ์˜ ๊นŠ์ด๊ฐ€ -1์ด๋ฉด ์•„์ง ๋ฐฉ๋ฌธ x) -> ๋…ธ๋“œ์˜ ๊นŠ์ด์™€ ๋…ธ๋“œ์˜ ๋ฐฉ๋ฌธ ์ˆœ์„œ ์ €์žฅ ํ›„ dfs ํ˜ธ์ถœ

* ๋…ธ๋“œ์˜ ๊นŠ์ด๋Š” ์ „ ๋…ธ๋“œ์˜ ๊นŠ์ด +1์ด๋‹ค.

 


๋งˆ๋ฌด๋ฆฌ๐Ÿค”