Separate paths

4.5

2 votes
Algorithms, Graphs
Problem

You are given a directed graph that contains N nodes (numbered from 1 to N) and M edges.

A valid path is a path that starts from a node that does not contain any edges that are directed towards it. That is, the value of Indegree of node is 0. This path can also contain only one node in it. That is, the paths of length 0 are also valid paths but they must still follow the main condition that the starting node (in this case the only node) should not contain any edges that are directed towards it.

You are required to calculate the number of unordered pair of nodes such that there exist two valid paths that end at these nodes. These two paths should not contain any node in common.

Note: The graph can be cyclic as well as disconnected, but there are no self-loops or multiple edges.

Input format

  • First line: A single integer T (1T10) denoting the number of test cases
  • For each test case:
    • First line: Two integers, N (2N500) and M (1Mmin(NN,105$$)) denoting the number of nodes and number of edges that are available in the graph respectively
    • Each of the next M lines: Two integers u and v (1u,vn,uv) denoting an edge from vertex u to vertex v

Note: As the input is very large, it is recommended to use fast I/O.

Output format

For each test case, print a single integer denoting the number of unordered pair of nodes that are satisfying the mentioned condition.

Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

For first test case, unordered pairs are: [(1,4), (1,5), (1,3), (2,4) , (2,5), (2,3), (3,4), (3,5)]. (3,5) is valid pair because there exist two separate valid paths ending at them, these paths are: 1->2->3 and 4->5. Similarly for others pairs also, there exist separate valid paths.

For second test case, unordered pairs are: [(1,4), (1,5), (1,6), (2,4), (2,5), (2,6), (3,4), (3,5), (3,6)].

For third and fourth test cases. no pairs exist as no two separate (no common node) valid paths exist.

Editor Image

?