728x90
반응형
https://www.acmicpc.net/problem/21276
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
static int N, M;
static int[] seq;
static String[] human;
static ArrayList<ArrayList<Integer>> grapgh;
static HashMap<String, Integer> people;
static TreeMap<String, ArrayList<Integer>> result;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
seq = new int[N];
human = new String[N];
grapgh = new ArrayList<>();
people = new HashMap<>();
result = new TreeMap<>();
for (int i = 0; i < N; i++) {
String name = st.nextToken();
human[i] = name;
grapgh.add(new ArrayList<>());
}
Arrays.sort(human);
for (int i = 0; i < N; i++) {
people.put(human[i], i);
result.put(human[i], new ArrayList<>());
}
M = Integer.parseInt(br.readLine());
while (M-- > 0) {
st = new StringTokenizer(br.readLine());
String u = st.nextToken();
String v = st.nextToken();
int uIdx = people.get(u);
int vIdx = people.get(v);
seq[uIdx]++;
grapgh.get(vIdx).add(uIdx);
}
topological();
}
static void topological() {
Queue<Integer> q = new LinkedList<>();
ArrayList<Integer> root = new ArrayList<>();
for (int i = 0; i < seq.length; i++) {
if (seq[i] == 0) {
q.offer(i);
root.add(i);
}
}
while (!q.isEmpty()) {
int cur = q.poll();
for (int next : grapgh.get(cur)) {
seq[next]--;
if (seq[next] == 0) {
q.offer(next);
result.get(human[cur]).add(next);
}
}
}
sb.append(root.size()).append("\n");
for (int idx : root) {
sb.append(human[idx]).append(" ");
}
sb.append("\n");
for (String name : result.keySet()) {
sb.append(name).append(" ").append(result.get(name).size()).append(" ");
result.get(name).sort(null);
for (int child : result.get(name)) {
sb.append(human[child]).append(" ");
}
sb.append("\n");
}
System.out.println(sb.toString());
}
}
|
cs |
728x90
'Algorithm > BOJ' 카테고리의 다른 글
백준) 1074_Z (0) | 2023.05.16 |
---|---|
백준) 11003_최솟값 찾기 (2) | 2023.05.14 |
백준) 1766_문제집 (1) | 2023.05.13 |
백준) 1005_ACM Craft (1) | 2023.05.13 |
백준) 14676_영우는 사기꾼? (2) | 2023.05.13 |