gt22 icon

Untitled

gt22 | PRO | 09/24/18 05:37:05 PM UTC | 0 ⭐ | 1095 👁️ | Never ⏰ | []
Java |

1.79 KB

|

None

|

0 👍

/

0 👎

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
 
public class O1742 {
 
 
    public static void main(String[] args) throws IOException {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(r.readLine());
        int[] funcGraph = new int[n];
        int[] degree = new int[n];
        for (int i = 0; i < n; i++) {
            funcGraph[i] = Integer.parseInt(r.readLine()) - 1;
            degree[funcGraph[i]]++;
        }
        int loopedVertices = 0;
        int loopCount = 0;
        int closedLoopCount = 0;
        int starterVerticles = 0;
        int[] visited = new int[n];
 
        for (int i = 0; i < n; i++) {
            if(degree[i] == 0) starterVerticles++;
 
            if(visited[i] != 0) continue;
 
            int j = 1;
            int cur = i;
            List<Integer> path = new ArrayList<>();
            while(visited[cur] == 0) {
                visited[cur] = j++;
                path.add(cur);
                cur = funcGraph[cur];
            }
            int size = j - visited[cur];
            List<Integer> loop = path.subList(visited[cur] - 1, path.size());
            boolean isClosed = true;
            for(int id : loop) {
                if(degree[id] > 1) {
                    isClosed = false;
                    break;
                }
            }
            loopedVertices += size;
            loopCount++;
            if(isClosed) {
                closedLoopCount++;
            }
        }
 
        System.out.print(starterVerticles + closedLoopCount);
        System.out.print(" ");
        System.out.println(n - loopedVertices + loopCount);
 
    }
 
}

Comments