|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + |
| 6 | + static int N, M; |
| 7 | + |
| 8 | + static ArrayList<HashSet<Integer>> setList = new ArrayList<>(); |
| 9 | + static ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); |
| 10 | + static int ans; |
| 11 | + |
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 15 | + N = Integer.parseInt(st.nextToken()); |
| 16 | + M = Integer.parseInt(st.nextToken()); |
| 17 | + |
| 18 | + for(int i = 0; i < N; i++) { |
| 19 | + setList.add(new HashSet<>()); |
| 20 | + graph.add(new ArrayList<>()); |
| 21 | + } |
| 22 | + |
| 23 | + for(int i = 0; i < M; i++) { |
| 24 | + st = new StringTokenizer(br.readLine()); |
| 25 | + int start = Integer.parseInt(st.nextToken()); |
| 26 | + int end = Integer.parseInt(st.nextToken()); |
| 27 | + |
| 28 | + graph.get(start-1).add(end-1); |
| 29 | + } |
| 30 | + |
| 31 | + for(int i = 0; i < N; i++) { |
| 32 | + bfs1(i); |
| 33 | + bfs2(i); |
| 34 | + } |
| 35 | + |
| 36 | + for(int i = 0; i < N; i++) { |
| 37 | + if(setList.get(i).size() == N-1) { |
| 38 | + ans++; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + System.out.println(ans); |
| 43 | + } |
| 44 | + |
| 45 | + public static void bfs1(int start) { |
| 46 | + ArrayDeque<Integer> q = new ArrayDeque<>(); |
| 47 | + |
| 48 | + q.add(start); |
| 49 | + |
| 50 | + boolean[] visited = new boolean[N]; |
| 51 | + |
| 52 | + while(!q.isEmpty()) { |
| 53 | + int cur = q.poll(); |
| 54 | + |
| 55 | + for(int x : graph.get(cur)) { |
| 56 | + if(visited[x]) |
| 57 | + continue; |
| 58 | + visited[x] = true; |
| 59 | + setList.get(x).add(start); |
| 60 | +// System.out.println("start : " + start + " x : " + x); |
| 61 | + q.offer(x); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + public static void bfs2(int start) { |
| 67 | + ArrayDeque<Integer> q = new ArrayDeque<>(); |
| 68 | + |
| 69 | + q.add(start); |
| 70 | + |
| 71 | + boolean[] visited = new boolean[N]; |
| 72 | + |
| 73 | + while(!q.isEmpty()) { |
| 74 | + int cur = q.poll(); |
| 75 | + |
| 76 | + for(int x : graph.get(cur)) { |
| 77 | + if(visited[x]) |
| 78 | + continue; |
| 79 | + visited[x] = true; |
| 80 | + setList.get(start).add(x); |
| 81 | +// System.out.println("start : " + start + " x : " + x); |
| 82 | + q.offer(x); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments