알고리즘
[BOJ] 25601 - 자바의 형변환 (Python, JavaScript)
흙금
2023. 5. 12. 08:36
아이디어
맵을 이용해 각 클래스의 부모 클래스 정보를 저장하고, 부모 클래스를 탐색하며 형변환이 가능한지 확인한다.
풀이 #1 (Python)
import sys
input = sys.stdin.readline
def solution():
N = int(input())
tree = dict()
for _ in range(N-1):
A, B = input().split()
tree[A] = B
A, B = input().split()
a = A
while a:
a = tree.get(a, '')
if a == B:
print(1)
return
b = B
while b:
b = tree.get(b, '')
if b == A:
print(1)
return
print(0)
solution()
풀이 #2 (JavaScript)
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().split('\n');
function solution() {
const N = Number(input[0]);
let tree = new Map();
for (let i=1; i<N; i++) {
const [A, B] = input[i].split(' ');
tree.set(A, B);
}
const [A, B] = input[N].split(' ');
let a = A;
while (a) {
a = tree.get(a);
if (a === B) {
console.log(1);
return;
}
}
let b = B;
while (b) {
b = tree.get(b);
if (b === A) {
console.log(1);
return;
}
}
console.log(0);
}
solution();