티스토리 뷰
줄세우기 문제는 DAG로 표현할 수 있다.
메모리 절약을 위해 간선의 연결 상태는 리스트로 표현한다.
노드에 입력이 들어는 것을 따로 배열로 표현하여 더이상 연결이 되지 않는 노드는 제거하면 된다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sdk.backjun.graph; | |
import java.util.HashMap; | |
import java.util.LinkedList; | |
import java.util.Queue; | |
import java.util.Scanner; | |
/** | |
* 백준, 2252, 위상정렬, 줄세우기 | |
* | |
* @author whitebeardk | |
* | |
*/ | |
public class Problem2252 { | |
static int N; // 문제의 수 | |
static int M; // 정보의 개수 | |
static HashMap<Integer, LinkedList<Integer>> maps = new HashMap<>(); | |
static int[] in; | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
N = sc.nextInt(); | |
M = sc.nextInt(); | |
in = new int[N + 1]; | |
for (int i = 0; i < M; i++) { | |
int from = sc.nextInt(); | |
int to = sc.nextInt(); | |
if (!maps.containsKey(from)) { | |
LinkedList<Integer> list = new LinkedList<>(); | |
maps.put(from, list); | |
} | |
// 노드의 연결상태를 링크드 리스트로 표현 | |
maps.get(from).add(to); | |
// 입력으로 들어오는 간선의 상태를 기록 | |
in[to]++; | |
} | |
sc.close(); | |
Queue<Integer> queue = new LinkedList<>(); | |
// 초기 시작점을 기록 | |
for (int i = 1; i < N + 1; i++) { | |
if (in[i] == 0) | |
queue.offer(i); | |
} | |
while (true) { | |
if (queue.size() == 0) | |
break; | |
int from = queue.poll(); | |
System.out.print(from + " "); | |
// 노드가 간선을 가지고 있으면 큐에 추가 | |
if (maps.containsKey(from)) { | |
for (int to : maps.get(from)) { | |
if (--in[to] == 0) | |
queue.add(to); | |
} | |
} | |
} | |
} | |
} |
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[백준][최단거리] 11657 타임머신(벨만포드 알고리즘) (0) | 2017.06.21 |
---|---|
[백준][다이나믹] 10844 쉬운계단수 (0) | 2017.06.21 |
[백준][다이나믹] 1520 내리막길 (0) | 2017.06.20 |
[백준][다이나믹] 2156 포도주 시식 (0) | 2017.06.19 |
[백준] 1003 피보나치 함수 (0) | 2017.06.01 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Tez
- 오류
- HDFS
- oozie
- Hadoop
- SPARK
- hbase
- ubuntu
- 백준
- Linux
- AWS
- 다이나믹
- mysql
- airflow
- S3
- yarn
- bash
- HIVE
- SQL
- Python
- 정올
- java
- emr
- 하이브
- error
- build
- 하둡
- nodejs
- 알고리즘
- 파이썬
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함