๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 15900_๋‚˜๋ฌด ํƒˆ์ถœ

๋ฟŒ์•ผ._. 2023. 7. 7. 17:43

Silver I

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

< ๋‚˜๋ฌด ํƒˆ์ถœ >

 

๋ฌธ์ œ ํ’€์ด 

 

๋ฃจํŠธ ๋…ธ๋“œ์—์„œ dfs๋ฅผ ํ™œ์šฉํ•ด์„œ ๋ชจ๋“  ์ •์ ์„ ๋ฐฉ๋ฌธํ•œ๋‹ค. ๋ฆฌํ”„ ๋…ธ๋“œ์— ๋„๋‹ฌํ•œ ๊ฒฝ์šฐ depth๋ฅผ ๊ตฌํ•ด ๋”ํ•ด์ค€๋‹ค.

๋ชจ๋“  ๋ฆฌํ”„ ๋…ธ๋“œ์— ๋„๋‹ฌํ–ˆ์„ ๋•Œ depth์˜ ํ•ฉ์ด ํ™€์ˆ˜์ด๋ฉด ๊ฒŒ์ž„์—์„œ ์ด๊ธธ ์ˆ˜ ์žˆ์œผ๋ฉฐ ์ง์ˆ˜์ด๋ฉด ๊ฒŒ์ž„์—์„œ ์ด๊ธธ ์ˆ˜ ์—†๋‹ค.

 

 my solution (Java)

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

public class _15900_ { // ๋‚˜๋ฌด ํƒˆ์ถœ
	static ArrayList<ArrayList<Integer>> arr;
	static int cnt;
	static boolean visited[];

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

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

		arr = new ArrayList<>();
		visited = new boolean[n + 1];
		for (int i = 0; i < n + 1; i++) {
			arr.add(new ArrayList<>());
		}

		for (int i = 0; i < n - 1; i++) {
			st = new StringTokenizer(bf.readLine());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());

			arr.get(a).add(b);
			arr.get(b).add(a);

		}

		cnt = 0;
		dfs(1, 0);

		if (cnt % 2 == 0)
			System.out.println("No");
		else
			System.out.println("Yes");
	}

	private static void dfs(int idx, int depth) {
		visited[idx] = true;
		int check=0;
		for (int i = 0; i < arr.get(idx).size(); i++) {
			if (visited[arr.get(idx).get(i)]) {
				check+=1;
				continue;
			}
			dfs(arr.get(idx).get(i), depth + 1);
		}
		if(check==arr.get(idx).size()) {
			cnt += depth;
			return;
		}
	}
}

 

Main

๋ณ€์ˆ˜)
n : ํŠธ๋ฆฌ์˜ ์ •์  ๊ฐœ์ˆ˜
arr : ํŠธ๋ฆฌ ์ •๋ณด
visited : ๋ฐฉ๋ฌธ ์—ฌ๋ถ€
cnt : ๋ชจ๋“  ๋ฆฌํ”„ ๋…ธ๋“œ์— ๋„๋‹ฌํ•  ๋•Œ depth์˜ ํ•ฉ

 

-ํŠธ๋ฆฌ์˜ ์ •์  ๊ฐœ์ˆ˜(n) ์ž…๋ ฅ

- ํŠธ๋ฆฌ์˜ ๊ฐ„์„  ์ •๋ณด๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์ €์žฅ (arr)

- dfs ํ•จ์ˆ˜ ํ˜ธ์ถœ

- cnt๊ฐ€ ํ™€์ˆ˜๋ผ๋ฉด ๊ฒŒ์ž„์—์„œ ์ด๊ธฐ๊ณ  ์ง์ˆ˜์ด๋ฉด ๊ฒŒ์ž„์—์„œ ์ง

 

dfs

- ํŠธ๋ฆฌ ์ •์  ๋ฐฉ๋ฌธ ํ‘œ์‹œ

- ์ •์ ๊ณผ ์—ฐ๊ฒฐ๋œ ์ •์  ์ค‘์—์„œ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ณณ์ด ์žˆ๋‹ค๋ฉด dfs ํ•จ์ˆ˜ ํ˜ธ์ถœ

- ์ •์ ๊ณผ ์—ฐ๊ฒฐ๋œ ์ •์  ์ค‘์—์„œ ๋ชจ๋‘ ๋‹ค ๋ฐฉ๋ฌธํ•œ ๊ณณ์ด๋ผ๋ฉด ๋ฆฌํ”„๋…ธ๋“œ๋ž€ ๋œป์ด๋ฏ€๋กœ depth๋ฅผ ๋”ํ•ด์คŒ