File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+ import java.io.* ;
4+ public class Main {
5+ static BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
6+ static BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (System . out));
7+ static StringTokenizer st;
8+ static int N ,M ;
9+ static List<Integer > [] adj;
10+ static int [] degree;
11+
12+ public static void main (String [] args ) throws IOException {
13+ st = new StringTokenizer (br. readLine());
14+ N = Integer . parseInt(st. nextToken());
15+ M = Integer . parseInt(st. nextToken());
16+ adj = new List [N + 1 ];
17+ degree = new int [N + 1 ];
18+
19+ for (int i = 1 ; i <= N ; i++ ) {
20+ adj[i] = new ArrayList<> ();
21+ }
22+
23+ for (int i = 0 ; i < M ; i++ ) {
24+ st = new StringTokenizer (br. readLine());
25+ int a = Integer . parseInt(st. nextToken());
26+ int b = Integer . parseInt(st. nextToken());
27+ adj[a]. add(b);
28+ degree[b]++ ;
29+ }
30+
31+
32+ BFS ();
33+ bw. close();
34+ }
35+ static void BFS () throws IOException {
36+ PriorityQueue<Integer > pq = new PriorityQueue<> ();
37+ for (int i = 1 ; i <= N ; i++ ) {
38+ if (degree[i] == 0 ){
39+ pq. add(i);
40+ }
41+ }
42+
43+ while (! pq. isEmpty()){
44+ int u = pq. poll();
45+ bw. write(u+ " " );
46+
47+ for (int v : adj[u]){
48+ if (-- degree[v] == 0 ){
49+ pq. add(v);
50+ }
51+ }
52+ }
53+ }
54+ }
55+
56+ ```
You can’t perform that action at this time.
0 commit comments