본문으로 바로가기

백준 14725번 개미굴 (JAVA)

category 알고리즘/백준 2021. 7. 25. 23:47

https://www.acmicpc.net/problem/14725

 

14725번: 개미굴

첫 번째 줄은 로봇 개미가 각 층을 따라 내려오면서 알게 된 먹이의 정보 개수 N개가 주어진다.  (1 ≤ N ≤ 1000) 두 번째 줄부터 N+1 번째 줄까지, 각 줄의 시작은 로봇 개미 한마리가 보내준 먹이

www.acmicpc.net

 

이 문제도 역시 전형적인 Trie 알고리즘 문제였다.

특별한 변형이 없으므로, 로직에 대한 설명은 생략한다.

 

package string;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.function.Function;

/*
 * 전형적인 Trie 알고리즘 문제.
 */

public class BOJ_14725_개미굴 {
	static Function<String, Integer> stoi = Integer::parseInt;
	static int N;
	static Trie root;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;

		N = stoi.apply(br.readLine());
		root = new Trie();
		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(br.readLine());
			int k = stoi.apply(st.nextToken());
			Node node = root.node;
			for (int j = 0; j < k; j++) {
				node = node.down.computeIfAbsent(st.nextToken(), s -> new Node());
			}
		}
		root.node.print(0);
	}

	static class Trie {
		Node node;

		Trie() {
			node = new Node();
		}

	}

	static class Node {
		Map<String, Node> down;

		Node() {
			down = new TreeMap<String, Node>();
		}

		public void print(int depth) {
			for (String s : down.keySet()) {
				for (int i = 0; i < depth; i++) {
					System.out.print("--");
				}
				System.out.println(s);
				down.get(s).print(depth + 1);
			}
		}
	}

}