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);
}
}
}
}
'알고리즘 > 백준' 카테고리의 다른 글
백준 6568번 귀도 반 로썸은 크리스마스날 심심하다고 파이썬을 만들었다 (JAVA) (0) | 2021.08.01 |
---|---|
백준 11779번 최소비용 구하기 2 (JAVA) (0) | 2021.07.25 |
백준 5670번 휴대폰 자판 (JAVA) (0) | 2021.07.25 |
백준 5373번 큐빙 (JAVA) (0) | 2021.07.25 |
백준 2533번 사회망서비스SNS (JAVA) (0) | 2021.07.12 |