|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + static StringTokenizer st; |
| 9 | + static int N,M; |
| 10 | + static List<Integer>[] adjList; |
| 11 | + static int[] degree; |
| 12 | + static int[] result; |
| 13 | + |
| 14 | + public static void main(String[] args) throws IOException { |
| 15 | + st = new StringTokenizer(br.readLine()); |
| 16 | + N = Integer.parseInt(st.nextToken()); |
| 17 | + M = Integer.parseInt(st.nextToken()); |
| 18 | + adjList = new List[N+1]; |
| 19 | + degree = new int[N+1]; |
| 20 | + result = new int[N]; |
| 21 | + |
| 22 | + for (int i = 1; i <= N; i++) { |
| 23 | + adjList[i] = new ArrayList<>(); |
| 24 | + } |
| 25 | + |
| 26 | + for (int i = 0; i < M; i++) { |
| 27 | + st = new StringTokenizer(br.readLine()); |
| 28 | + int cnt = Integer.parseInt(st.nextToken()); |
| 29 | + int[] order = new int[cnt]; |
| 30 | + for (int j = 0; j < cnt; j++) { |
| 31 | + order[j] = Integer.parseInt(st.nextToken()); |
| 32 | + } |
| 33 | + for (int j = 0; j < cnt-1; j++) { |
| 34 | + for (int k = j+1; k < cnt; k++) { |
| 35 | + if(!adjList[order[j]].contains(order[k])) { |
| 36 | + adjList[order[j]].add(order[k]); |
| 37 | + degree[order[k]]++; |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + if(go() == N){ |
| 44 | + for (int i = 0; i < N; i++) { |
| 45 | + bw.write(result[i]+"\n"); |
| 46 | + } |
| 47 | + }else{ |
| 48 | + bw.write("0"); |
| 49 | + } |
| 50 | + bw.close(); |
| 51 | + } |
| 52 | + public static int go(){ |
| 53 | + int cnt = 0; |
| 54 | + ArrayDeque<Integer> q = new ArrayDeque<>(); |
| 55 | + for (int i = 1; i <= N; i++) { |
| 56 | + if(degree[i] == 0){ |
| 57 | + q.add(i); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + while(!q.isEmpty()){ |
| 62 | + int cur = q.poll(); |
| 63 | + result[cnt++] = cur; |
| 64 | + for(int next : adjList[cur]){ |
| 65 | + if(--degree[next] == 0){ |
| 66 | + q.add(next); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + return cnt; |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
0 commit comments