using
System;
using
System.Collections.Generic;
public
class
OrderedSet
{
private
Dictionary<
int
, HashSet<
int
>> tree =
new
Dictionary<
int
, HashSet<
int
>>();
public
void
Insert(
int
val)
{
tree[val] =
new
HashSet<
int
>();
}
public
bool
IsSubsetOf(OrderedSet other)
{
return
new
HashSet<
int
>(tree.Keys).IsSubsetOf(other.tree.Keys);
}
public
int
CountSmaller(
int
val)
{
int
count = 0;
foreach
(
int
k
in
tree.Keys)
{
if
(k < val)
{
count++;
}
}
return
count;
}
public
void
Erase(
int
val)
{
tree.Remove(val);
}
}
public
class
Program
{
private
static
Dictionary<
int
,
int
> ans =
new
Dictionary<
int
,
int
>();
private
static
void
AddEdge(Dictionary<
int
, List<
int
>> adj,
int
u,
int
v)
{
adj[u].Add(v);
adj[v].Add(u);
}
private
static
void
CountSmallerAncestors(Dictionary<
int
, List<
int
>> adj,
int
root,
int
par, OrderedSet ancestors)
{
ans[root] = ancestors.CountSmaller(root);
ancestors.Insert(root);
foreach
(
int
node
in
adj[root])
{
if
(node != par)
{
CountSmallerAncestors(adj, node, root, ancestors);
}
}
ancestors.Erase(root);
}
public
static
void
Main()
{
int
N = 7;
Dictionary<
int
, List<
int
>> adj =
new
Dictionary<
int
, List<
int
>>();
for
(
int
i = 1; i <= N; i++)
{
adj[i] =
new
List<
int
>();
}
AddEdge(adj, 1, 5);
AddEdge(adj, 1, 4);
AddEdge(adj, 4, 6);
AddEdge(adj, 5, 3);
AddEdge(adj, 5, 2);
AddEdge(adj, 5, 7);
OrderedSet ancestors =
new
OrderedSet();
CountSmallerAncestors(adj, 1, -1, ancestors);
for
(
int
i = 1; i <= N; i++)
{
Console.Write(ans[i] +
" "
);
}
}
}