using
System;
using
System.Collections.Generic;
class
GFG {
static
bool
CanConstruct(
int
[] originalSeq,
int
[][] sequences)
{
List<
int
> sortedOrder =
new
List<
int
>();
if
(originalSeq.Length <= 0) {
return
false
;
}
Dictionary<
int
,
int
> inDegree
=
new
Dictionary<
int
,
int
>();
Dictionary<
int
, List<
int
> > graph
=
new
Dictionary<
int
, List<
int
> >();
foreach
(
int
[] seq
in
sequences)
{
for
(
int
i = 0; i < seq.Length; i++) {
inDegree[seq[i]] = 0;
graph[seq[i]] =
new
List<
int
>();
}
}
foreach
(
int
[] seq
in
sequences)
{
for
(
int
i = 1; i < seq.Length; i++) {
int
parent = seq[i - 1], child = seq[i];
graph[parent].Add(child);
inDegree[child] = inDegree[child] + 1;
}
}
if
(inDegree.Count != originalSeq.Length) {
return
false
;
}
List<
int
> sources =
new
List<
int
>();
foreach
(KeyValuePair<
int
,
int
> entry
in
inDegree)
{
if
(entry.Value == 0) {
sources.Add(entry.Key);
}
}
while
(sources.Count > 0) {
if
(sources.Count > 1) {
return
false
;
}
if
(originalSeq[sortedOrder.Count]
!= sources[0]) {
return
false
;
}
int
vertex = sources[0];
sources.RemoveAt(0);
sortedOrder.Add(vertex);
List<
int
> children = graph[vertex];
foreach
(
int
child
in
children)
{
inDegree[child] = inDegree[child] - 1;
if
(inDegree[child] == 0) {
sources.Add(child);
}
}
}
return
sortedOrder.Count == originalSeq.Length;
}
static
void
Main(
string
[] args)
{
int
[] arr = { 1, 2, 6, 7, 3, 5, 4 };
int
[][] seqs = {
new
int
[] { 1, 2, 3 },
new
int
[] { 7, 3, 5 },
new
int
[] { 1, 6, 3, 4 },
new
int
[] { 2, 6, 5, 4 } };
bool
result = CanConstruct(arr, seqs);
if
(result)
Console.WriteLine(
"Yes"
);
else
Console.WriteLine(
"No"
);
}
}