gt22

Untitled

Sep 24th, 2018
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6.  
  7. public class O1742 {
  8.  
  9.  
  10.     public static void main(String[] args) throws IOException {
  11.         BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
  12.         int n = Integer.parseInt(r.readLine());
  13.         int[] funcGraph = new int[n];
  14.         int[] degree = new int[n];
  15.         for (int i = 0; i < n; i++) {
  16.             funcGraph[i] = Integer.parseInt(r.readLine()) - 1;
  17.             degree[funcGraph[i]]++;
  18.         }
  19.         int loopedVertices = 0;
  20.         int loopCount = 0;
  21.         int closedLoopCount = 0;
  22.         int starterVerticles = 0;
  23.         int[] visited = new int[n];
  24.  
  25.         for (int i = 0; i < n; i++) {
  26.             if(degree[i] == 0) starterVerticles++;
  27.  
  28.             if(visited[i] != 0) continue;
  29.  
  30.             int j = 1;
  31.             int cur = i;
  32.             List<Integer> path = new ArrayList<>();
  33.             while(visited[cur] == 0) {
  34.                 visited[cur] = j++;
  35.                 path.add(cur);
  36.                 cur = funcGraph[cur];
  37.             }
  38.             int size = j - visited[cur];
  39.             List<Integer> loop = path.subList(visited[cur] - 1, path.size());
  40.             boolean isClosed = true;
  41.             for(int id : loop) {
  42.                 if(degree[id] > 1) {
  43.                     isClosed = false;
  44.                     break;
  45.                 }
  46.             }
  47.             loopedVertices += size;
  48.             loopCount++;
  49.             if(isClosed) {
  50.                 closedLoopCount++;
  51.             }
  52.         }
  53.  
  54.         System.out.print(starterVerticles + closedLoopCount);
  55.         System.out.print(" ");
  56.         System.out.println(n - loopedVertices + loopCount);
  57.  
  58.     }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment