๋ฌธ์ (์ถ์ฒ: 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๋ฅผ ๋ํด์ค

'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Baekjoon] 2075_N๋ฒ์งธ ํฐ ์ (0) | 2023.07.13 | 
|---|---|
| [Baekjoon] 5525_IOIOI (0) | 2023.07.11 | 
| [Baekjoon] 15903_์นด๋ ํฉ์ฒด ๋์ด (0) | 2023.07.02 | 
| [Baekjoon] 16918_๋ด๋ฒ๋งจ (0) | 2023.06.30 | 
| [Baekjoon] 3584_๊ฐ์ฅ ๊ฐ๊น์ด ๊ณตํต ์กฐ์ (1) | 2023.06.29 |