π λ¬Έμ
https://www.acmicpc.net/problem/22856
π μμ΄λμ΄
λ§μ½ νμ¬ λ Έλκ° μ μ¬ μ€μ μνμ λμ΄λΌλ©΄ μ μ¬ μμλ₯Ό μ’ λ£νλ€λ λΆλΆμ μλͺ» μ΄ν΄ν΄μ μ¬λ¬ λ² νλ Έλ λ¬Έμ μμ΅λλ€. μ΄ κ΅¬λ¬Έμ νμ¬ λ Έλκ° μ€μ μνκ° λλ¬λ€λ©΄ λ€μ μ¬λΌκ°μ§ μμλ λλ€λ κ²μ μλ―Έν©λλ€. μ¦ μΌμͺ½μΌλ‘ κ°λ κ²½μ°λ λ°λμ 루νΈλ‘ λ€μ μ¬λΌμμΌ νμ§λ§ μ€λ₯Έμͺ½μ κ²½μ°λ μ€μμνκ° λλ μνλΌλ©΄ λ€μ μ¬λΌμ€μ§ μμλ λ©λλ€. (μ€μ μν : μΌμͺ½ μμ -> root -> μ€λ₯Έμͺ½ μμ)
λ°λΌμ μΌμͺ½ μμμ κ°λ κ²½μ°λ λ΄λ €κ°λ€ μ¬λΌμ€λ μ μλ₯Ό λͺ¨λ μΈ μ£Όμμ§λ§
μ€λ₯Έμͺ½ μμμΌλ‘ κ°λκ²½μ°λ λͺ¨λ λ Έλλ₯Ό λ°©λ¬Έν μνλΌλ©΄ λ€μ μ¬λΌμ€μ§ μκ³ μ’ λ£νλλ‘ νμμ΅λλ€.
π νμ΄
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Boj_22856_νΈλ¦¬μν {
private static class Node {
int root;
Node left;
Node right;
public Node(int root) {
this.root = root;
}
public void set(Node left, Node right) {
this.left = left;
this.right = right;
}
}
private static int visitedCnt = 0;
private static boolean[] visited;
private static int n;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
n = Integer.parseInt(br.readLine());
Node[] nodes = new Node[n];
visited = new boolean[n];
for (int i = 0; i < n; i++) {
nodes[i] = new Node(i);
}
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken()) - 1;
int left = Integer.parseInt(st.nextToken()) - 1;
int right = Integer.parseInt(st.nextToken()) - 1;
if (left != -2 && right != -2) {
nodes[a].set(nodes[left], nodes[right]); //μμμ΄ μλκ²½μ°
} else if (left != -2) {
nodes[a].set(nodes[left], null); //μΌμͺ½ μμλ§ μλ κ²½μ°
} else if (right != -2) {
nodes[a].set(null, nodes[right]); //μ€λ₯Έμͺ½ μμλ§ μλ κ²½μ°
}
}
System.out.println(dfs(nodes[0]));
}
private static int dfs(Node now) {
//μΌμͺ½λ§ μμΌλ©΄ λ€μ μ¬λΌκ°μΌ νκ³
//μ€λ₯Έμͺ½μμ μ€μ μνκ° λλ¬μΌλ©΄ μ¬λΌκ°μ§ μμλ λ¨
int score = 0;
if (now.left != null && !visited[now.left.root]) {
score++; //λ΄λ €κ°λ λΉμ©
score += dfs(now.left);
score++; //λ€μ μ¬λΌκ°λ λΉμ©
}
//μ€μ μνν¨μ 체ν¬νλ€.
visited[now.root] = true;
visitedCnt++;
if (now.right != null && !visited[now.right.root]) {
score++; //λ΄λ €κ°λ λΉμ©
score += dfs(now.right);
if (visitedCnt == n) { //μ€λ₯Έμͺ½μμ μ€μ μνκ° μ’
λ£λμλ€.λ€μ μ¬λΌκ°μ§ μμλ λλ€.
return score;
}
score++;
}
return score;
}
}