๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Problem Solving

[Java] ๋ฐฑ์ค€ 31423 - ์‹ ์ดŒ ํ†ตํํ•ฉ ๊ณ„ํš

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