

The range of elements in the ‘secondary’ sequence varies from 1 to N.
If primary = [ 1, 2, 3 ] and secondary = [ [ 1, 2 ], [ 1, 3 ] ]
[ 1, 2, 3 ] is shortest common supersequence of [ 1, 2 ] and [ 1, 3 ]. But [ 1, 3, 2 ] is also a shortest common super sequence of [ 1, 2 ] and [ 1, 3 ]. As [ 1, 2, 3 ] is not the only shortest supersequence, you need to return false.
The first line contains ‘ T ‘, denoting the number of test cases.
The first line of each test case contains three space-separated integers, N - number of elements in ‘primary’ sequence, ‘ X ‘ - number of sequences in ‘secondary’ sequence, and ‘ Y ‘ - number of elements in each sequence of ‘secondary’ sequence.
Each test case’s second line contains ‘ N ’ space-separated integers denoting elements of the ‘primary’ sequence.
The following ‘ X ‘ lines of each test case contain ‘ Y ‘ space-separated integers.
For each test case, return “ True “ if ‘primary’ is the only shortest supersequence of all the sequences in the ‘secondary’ sequence. Otherwise, return “ False “.
Print the output of each test case in a separate line.
1 <= T <= 10
1 <= N <= 10^5
1 <= primary[ i ] <= N
1 <= X, Y <= 10^3
Time Limit: 1 sec
We will represent the sequences in the ‘secondary’ sequence by a directed graph and find its topological sort order. If there is only one topological sort order, then we can say that the ‘primary’ sequence is the only shortest common supersequence.
At first, if the number of distinct elements in all the sequences in ‘secondary’ is less than the number of elements in ‘primary,’ i.e., ‘N’, then ‘primary’ can never be the shortest common supersequence.
We will calculate indegree for every vertex of the graph and find the vertices having ‘0’ indegree. Suppose at any moment there come two vertices with ‘0’ indegree. In that case, that means we have two choices for the topological sort order, and there can never be a unique common supersequence; otherwise, we will add this vertex to the topological sort order and decrement the in-degree of all the vertices connected to it.
If the topological sort order is the same as the ‘primary’ sequence, then we can say that the ‘primary’ sequence is the shortest common super sequence of all the sequences in ‘secondary’.
Algorithm
Let us understand the above approach with an example.
Let primary = [ 1, 2, 3 ] and secondary = [ [ 1, 2 ], [ 1, 3 ] ].
‘ adj ’ map will contain values as -
1 -> 2 , 3
2 -> Null
3 -> Null
‘indegree’ map will contain values as
1 -> 0
2 -> 1
3 -> 1
Now we will push elements with ‘ 0 ‘ indegree and decrement indegree of all vertices connected to it.
Initially push ‘ 1’ to ‘res’ and decrement indegree of ‘2’ and ‘3.’
Now Indegree of both ‘2’ and ‘3’ are ‘0’, which means we have two choices, and the supersequence can not be unique. So the answer will be false.