-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #20 from AlgoLeadMe/6-Me-in-U
6-Me-in-U
- Loading branch information
Showing
2 changed files
with
55 additions
and
1 deletion.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package BAEKJOON.Gold.Gold_III.P2252๋ฒ_์ค_์ธ์ฐ๊ธฐ; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.InputStreamReader; | ||
import java.util.LinkedList; | ||
import java.util.Queue; | ||
import java.util.StringTokenizer; | ||
|
||
public class Main { | ||
protected static int[] inDegree; | ||
protected static LinkedList<Integer>[] graph; | ||
|
||
public static void main(String[] args) throws IOException { | ||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | ||
StringTokenizer st = new StringTokenizer(br.readLine()); | ||
int N = Integer.parseInt(st.nextToken()); | ||
int M = Integer.parseInt(st.nextToken()); | ||
inDegree = new int[N + 1]; | ||
graph = new LinkedList[N + 1]; | ||
for (int i = 0; i < N + 1; i++) { | ||
graph[i] = new LinkedList<>(); | ||
} | ||
for (int j = 0; j < M; j++) { | ||
st = new StringTokenizer(br.readLine()); | ||
int A = Integer.parseInt(st.nextToken()); | ||
int B = Integer.parseInt(st.nextToken()); | ||
graph[A].add(B); | ||
inDegree[B]++; | ||
} | ||
System.out.println(topologySort(N)); | ||
} | ||
|
||
public static String topologySort(int N) { | ||
StringBuilder sb = new StringBuilder(); | ||
Queue<Integer> queue = new LinkedList<>(); | ||
for (int i = 1; i < N + 1; i++) { | ||
if (inDegree[i] == 0) { | ||
queue.add(i); | ||
} | ||
} | ||
while (!queue.isEmpty()) { | ||
int now = queue.poll(); | ||
sb.append(now).append(' '); | ||
for (int next : graph[now]) { | ||
if (--inDegree[next] == 0) { | ||
queue.add(next); | ||
} | ||
} | ||
} | ||
return sb.toString(); | ||
} | ||
} |