Problem Solving
[Java] ๋ฐฑ์ค 31423 - ์ ์ด ํตํํฉ ๊ณํ
336699go
2024. 2. 21. 12:53
https://www.acmicpc.net/problem/31423
ํ์ด
์ฝ์ด๋ณด๋ฉด ์ฐ๊ฒฐ ๋ฆฌ์คํธ๊ฐ ๋ ์ค๋ฅด๋ ๋ฌธ์
๋ค๋ง ํ๋ฒํ ์ฐ๊ฒฐ ๋ฆฌ์คํธ๋ก ํ๋ฉด ๋ค์ ์ด์ด ๋ถ์ด๋ ๊ณผ์ ์์ ๋งค๋ฒ head์์
๋ถํฐ tail๊น์ง ํ์ํด ๋๊ฐ๊ธฐ ๋๋ฌธ์ ์ด ์๊ฐ ๋ณต์ก๋๊ฐ O(N^2)์ด ๋์ด๋ฒ๋ฆผ
๊ทธ๋์ ๋ ธ๋๋ง๋ค tail ๊ฐ์ ๋๊ณ ๋งค๋ฒ next์ tail ๊ฐ์ ์ ์ ๋ฐ์ดํธํด ์ค์ผ ํจ
๋ค๋ฅธ ์ฌ๋๋ค ํ์ด ๋ณด๋ ๊ทธ๋ํ๋ก ์๊ฐํด์ DFS๋ก๋ ํ์ด๊ฐ ๊ฐ๋ฅํ ๊ฒ ๊ฐ๋ค
์ฝ๋
๋๋ณด๊ธฐ
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
String[] s = new String[N + 1];
int[] next = new int[N + 1];
int[] tail = new int[N + 1];
for (int i = 1; i <= N; i++) {
s[i] = br.readLine();
next[i] = i;
tail[i] = i;
}
int cur = -1;
for (int i = 0; i < N - 1; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int left = Integer.parseInt(st.nextToken());
int right = Integer.parseInt(st.nextToken());
next[tail[left]] = right;
tail[left] = tail[right];
cur = left;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
sb.append(s[cur]);
cur = next[cur];
}
System.out.println(sb);
br.close();
}
}
ํ ์คํธ ์ผ์ด์ค
๋๋ณด๊ธฐ
Input:
5
a
b
c
d
e
4 5
3 4
2 3
1 2
Expected output:
abcde
Input:
6
a
b
c
d
e
f
5 6
4 5
2 3
1 2
1 4
Expected output:
abcdef
Input:
2
a
b
2 1
Expected output:
ba