https://www.acmicpc.net/problem/21276
νμ΄
- μ‘°μ-μμ κ΄κ³λ₯Ό μ΄μ©ν΄μ μμ μ λ ¬
- λΆλͺ¨-μμ κ΄κ³λ₯Ό μΆλ ₯νλ 건 μ 체 μΆλ ₯μμ μμμ μ΄λ¦μ΄ ν λ²λ§ λ±μ₯νλ€λ μ μ μ΄μ©ν μ μμ. κ°μ₯ λ°μμ λΆν° μλ‘ μ¬λΌκ°λ©΄μ μμλ€μ μΆλ ₯νλλ° μ΄λ―Έ λμ¨ μ΄λ¦μ μΆλ ₯νμ§ μλλ‘ νλ©΄ λ¨.
- λ¬Έμμ΄ μ²λ¦¬λ₯Ό μν΄ HashMap μ¬μ©
μ½λ
λ보기
import java.io.*;
import java.util.*;
public class Main {
public static class Person {
public String name;
public int indegree, outdegree;
public ArrayList<Person> ancestors;
public ArrayList<Person> descendants;
public ArrayList<String> children;
public Person(String name) {
this.name = name;
indegree = 0;
outdegree = 0;
ancestors = new ArrayList<>();
descendants = new ArrayList<>();
children = new ArrayList<>();
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
HashMap<String, Person> map = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
ArrayList<String> progenitors = new ArrayList<>();
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
String name = st.nextToken();
Person p = new Person(name);
list.add(name);
map.put(name, p);
}
int M = Integer.parseInt(br.readLine());
while (M-- > 0) {
st = new StringTokenizer(br.readLine());
String descendant = st.nextToken();
String ancestor = st.nextToken();
map.get(descendant).ancestors.add(map.get(ancestor));
map.get(descendant).outdegree++;
map.get(ancestor).indegree++;
}
Stack<Person> stack = new Stack<>();
HashSet<Person> usedChildren = new HashSet<>();
int K = 0;
for (String name : map.keySet()) {
if (map.get(name).indegree == 0) {
stack.add(map.get(name));
}
if (map.get(name).outdegree == 0) {
progenitors.add(name);
K++;
}
}
while (!stack.empty()) {
Person cur = stack.pop();
for (Person p : cur.descendants) {
if (!usedChildren.contains(p)) {
usedChildren.add(p);
cur.children.add(p.name);
}
}
for (Person p : cur.ancestors) {
p.descendants.add(cur);
if (--p.indegree == 0) {
stack.add(p);
}
}
}
StringBuilder sb = new StringBuilder().append(K).append('\n');
Collections.sort(progenitors);
Collections.sort(list);
for (String name : progenitors) {
sb.append(name).append(' ');
}
sb.append('\n');
for (String name : list) {
sb.append(name).append(' ').append(map.get(name).children.size());
Collections.sort(map.get(name).children);
for (String childName : map.get(name).children) {
sb.append(' ').append(childName);
}
sb.append('\n');
}
System.out.println(sb);
br.close();
}
}
νκΈ°
λ΄κ° μλ Ήμ΄ μλ κ±΄μ§ κ΅¬ννλλ° μ΄κ² μ κ² μ κ²½ μ°μ΄λ κ² λ§μλ λ¬Έμ ,,
μμμμ μ‘°μμΌλ‘ μ¬λΌμ€κΈ° 보λ€λ μλ°©ν₯μΌλ‘ λ΄λ €μ€λ κ² λ μ½λ€λ κ² κ°λ€
'Problem Solving' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[Java] λ°±μ€ 16724 - νΌλ¦¬ λΆλ μ¬λμ΄ (0) | 2024.03.28 |
---|---|
[Java] λ°±μ€ 7579 - μ± (0) | 2024.03.27 |
[Java] λ°±μ€ 31577 - λμ¬μ¨μ΄μ λΉνΈμ½μΈ (0) | 2024.03.22 |
[Java] λ°±μ€ 31623 - Room Temperature (0) | 2024.03.21 |
[Java] λ°±μ€ 31443 - μ€μμ΄ (1) | 2024.03.15 |