using
System;
using
System.Collections.Generic;
public
class
GFG {
static
void
DFS(
int
node,
int
par,
Dictionary<
int
, List<KeyValuePair<
int
,
int
> > >
graph,
bool
[] visited,
int
[] edgeRev,
int
d,
int
[] depth,
ref
int
totalReversals)
{
visited[node] =
true
;
depth[node] = d;
foreach
(
var
child
in
graph[node])
{
if
(!visited[child.Key]) {
edgeRev[child.Key]
= edgeRev[node] + child.Value;
totalReversals += child.Value;
DFS(child.Key, node, graph, visited,
edgeRev, d + 1, depth,
ref
totalReversals);
}
}
}
static
List<
int
>
MinimumEdgeReversals(
int
n, List<List<
int
> > edges)
{
List<
int
> res =
new
List<
int
>(
new
int
[n]);
int
[] depth =
new
int
[n];
bool
[] visited =
new
bool
[n];
int
[] edgeRev =
new
int
[n];
int
totalReversals = 0;
Dictionary<
int
, List<KeyValuePair<
int
,
int
> > >
graph =
new
Dictionary<
int
, List<KeyValuePair<
int
,
int
> > >();
int
startNode = 0;
foreach
(
var
edge
in
edges)
{
int
u = edge[0], v = edge[1];
if
(!graph.ContainsKey(u))
graph[u]
=
new
List<KeyValuePair<
int
,
int
> >();
if
(!graph.ContainsKey(v))
graph[v]
=
new
List<KeyValuePair<
int
,
int
> >();
graph[u].Add(
new
KeyValuePair<
int
,
int
>(v, 0));
graph[v].Add(
new
KeyValuePair<
int
,
int
>(u, 1));
}
DFS(startNode, -1, graph, visited, edgeRev, 0,
depth,
ref
totalReversals);
res[startNode] = totalReversals;
for
(
int
i = 0; i < n; i++) {
if
(i == startNode)
continue
;
int
xToRootRev = depth[i] - edgeRev[i];
int
rootToRem = totalReversals - edgeRev[i];
res[i] = xToRootRev + rootToRem;
}
return
res;
}
static
public
void
Main()
{
int
n = 4;
List<List<
int
> > edges =
new
List<List<
int
> >() {
new
List<
int
>() { 2, 0 },
new
List<
int
>() {
2, 1
},
new
List<
int
>() { 1, 3 }
};
List<
int
> res = MinimumEdgeReversals(n, edges);
foreach
(
var
val
in
res)
{
Console.Write(val +
" "
);
}
}
}