티스토리 뷰
접근 방법
- 순서가 있는 노드... 위상 정렬이 절로 떠오르는 문제 설명이다. 위상 정렬 알고리즘을 구현하기만 하면 정답을 맞출 수 있는 문제이다.
- 입력 제한을 보면 가수가 최대 1000명이 나온다고 하니까 O(N ** 2)까지 두고 풀어도 널널한 느낌이기 때문에, 빈 배열을 찾을 때 그냥 단순 순회하도록 구현한다.
- 차례대로 뺄 노드를 담을 Queue를 하나 만든다.
- 각 노드에 대한 조건 노드를 리스트로 둔다.
- Queue에서 노드를 하나씩 뺄 때마다 모든 노드를 순회하면서 뺀 노드가 존재한다면 리스트에서 빼준다.
- 위의 단계를 진행한 결과 빈 리스트가 나오게 된다면, 해당 노드를 Queue에 추가해준다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] nm = br.readLine().split(" ");
int n = Integer.parseInt(nm[0]);
int m = Integer.parseInt(nm[1]);
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int i = 1; i <= n; i++) map.put(i, new HashSet<>());
// per PD
for (int i = 0; i < m; i++) {
String[] orders = br.readLine().split(" ");
if (orders.length == 1) continue;
for (int j = 2; j < orders.length; j++) {
int node = Integer.parseInt(orders[j]);
if (!map.containsKey(node))
map.put(node, new HashSet<>());
map.get(node).add(Integer.parseInt(orders[j - 1]));
}
}
Deque<Integer> q = new ArrayDeque<>();
List<Integer> answer = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (map.get(i).size() == 0) q.add(i);
}
while (!q.isEmpty()) {
int currentNode = q.pollFirst();
answer.add(currentNode);
for (int i = 1; i <= n; i++) {
if (map.get(i).contains(currentNode)) {
map.get(i).remove(currentNode);
if(map.get(i).size() == 0) q.add(i);
}
}
}
if (answer.size() != n) System.out.println(0);
else for (int num : answer) System.out.println(num);
}
}
복기
배열 및 래퍼 클래스를 다룰 때는 항상 null 조건을 생각하고 코딩하기
'Algorithm' 카테고리의 다른 글
등산코스 정하기 (Python) (0) | 2023.09.19 |
---|---|
광고 삽입 (Java) (0) | 2023.09.17 |
표현 가능한 이진트리 (Java) (0) | 2023.09.14 |
가장 긴 팰린드롬 (Java) (0) | 2023.09.10 |
연속 펄스 부분 수열의 합 (Python) (0) | 2023.09.05 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- kotlin
- spring boot
- 인덱스
- 프로그래머스
- Everything Everywhere All at Once
- Docker
- DB
- 듄 파트 2
- 행동분석
- dfs
- csv
- 샤딩
- 정규화
- 역직렬화
- tree
- 리뷰
- 이해
- 영화
- 인문
- 후기
- dp
- protobuf
- 누적합
- 하이재킹
- json
- 영화 후기
- 직렬화
- cicd
- 듄
- 파티셔닝
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함