Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 내부 클래스
- Scanner
- 객체 지향
- java
- 상속
- nextInt
- python
- 17472
- 캡슐화
- enum
- 열거형
- 생성자
- abstract
- Final
- 제네릭
- 최소신장트리
- 추상화
- 버퍼비우기
- inheritance
- polymorphism
- 와일드카드
- 다형성
- this
- 프림알고리즘
- 백준
- 인터페이스
- Encapsulation
- 추상 클래스
- 객체지향
Archives
- Today
- Total
쫑쫑이의 블로그
백준 1766 문제집 Java [위상정렬, 우선순위 큐] 본문
https://www.acmicpc.net/problem/1766
위상정렬과 우선순위큐를 사용해서 풀이하면 된다
입력 값에 맞게 가중치를 추가해주고
1부터 N까지 가중치가 0인 값만 우선순위큐에 넣어준 후
우선순위큐에서 하나씩 꺼내면서 출력값에 추가하고
꺼낸 값이 방문할 수 있는 문제 번호의 가중치를 감소하고
가중치가 0이 되면 우선순위큐에 넣는 과정을 반복한다
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
PriorityQueue<Integer> queue = new PriorityQueue<>();
int[] degree = new int[N + 1];
ArrayList<Integer>[] next = new ArrayList[N + 1];
for (int i = 1; i <= N; i++) next[i] = new ArrayList<>();
for (int m = 0; m < M; m++) {
st = new StringTokenizer(br.readLine());
int A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
degree[B]++;
next[A].add(B);
}
for (int i = 1; i <= N; i++) {
if (degree[i] == 0) queue.add(i);
}
while (!queue.isEmpty()) {
int now = queue.poll();
sb.append(now).append(" ");
for (int n : next[now]) {
degree[n]--;
if (degree[n] == 0) queue.add(n);
}
}
sb.setLength(sb.length() - 1);
System.out.println(sb);
}
}
'알고리즘 > 백준' 카테고리의 다른 글
백준 2568 전깃줄 - 2 Java [LIS] (0) | 2022.11.11 |
---|---|
백준 4386 별자리 만들기 Java [최소스패닝트리, 프림] (0) | 2022.11.10 |
백준 1005 ACM Craft Java [위상정렬] (0) | 2022.11.07 |
백준 2623 음악프로그램 Java [위상정렬] (0) | 2022.11.06 |
백준 1647 도시 분할 계획 Java [최소스패닝트리, 프림] (0) | 2022.10.27 |