#K71082. Minimum Cameras Surveillance

    ID: 33452 Type: Default 1000ms 256MiB

Minimum Cameras Surveillance

Minimum Cameras Surveillance

You are given a building represented by a directed graph with N nodes and E corridors. Each corridor is a one‐way passage between two rooms. In addition, an entry point is provided, though it is not used in the calculation.

Your task is to calculate the minimum number of cameras required to monitor all movements within the building. A camera can fully monitor a connected set of corridors if the underlying directed graph is entirely reachable via a topological ordering. More formally, if the graph has a topological order (i.e. all nodes are reached), then one camera is enough; otherwise, for each disconnected component (where some nodes are unreachable by the topological sort), you must add one camera per component.

Note: The solution uses a modified version of Kahn's algorithm for topological sorting and then performs a breadth-first search (BFS) to count unreachable components.

The answer should be computed for multiple test cases. Each test case begins with a line containing two integers E and N, followed by a line with an entry point (an integer), and then E lines each containing two integers representing a corridor from one room to another. The entire input ends with a line "0 0".

The final answer for each test case is printed on a separate line.

inputFormat

The input consists of multiple test cases. Each test case is formatted as follows:

  1. A line with two integers E and N, where E is the number of corridors and N is the number of nodes (rooms).
  2. A line with a single integer representing the entry point (this value is not used in the calculation).
  3. E lines each containing two integers u and v indicating a directed corridor from room u to room v.

The test cases end when a line with "0 0" is encountered.

outputFormat

For each test case, print a single integer on a separate line representing the minimum number of cameras required to monitor the building.

## sample
4 5
0
0 1
0 2
2 3
3 4
5 6
1
0 1
1 2
2 3
3 4
4 5
0 0
1

1

</p>