// C# program to Count
// Simple Paths in given Tree
using System;
using System.Collections.Generic;
class GFG
{
// Function to traverse the given tree using DFS
static int
DFS(int len, int[] V, int root, int parent, int f,
Dictionary<int, int> freq,
Dictionary<int, List<int>> graph)
{
len++;
int val = V[root - 1];
// Frequency map
freq[val] = freq.GetValueOrDefault(val, 0) + 1;
int newfreq = Math.Max(f, freq[val]);
int requirefreq = (len + 1) / 2;
int ans = 0;
if (newfreq >= requirefreq)
ans++;
f = newfreq;
foreach (int it in graph[root])
{
if (it != parent)
{
ans += DFS(len, V, it, root, f, freq,
graph);
}
}
freq[val] = freq[val] - 1;
return ans;
}
// Wrapper function to call dfs function
static int FindTotalPath(int n, int[,] edges, int[] V)
{
// Adjacency list
Dictionary<int, List<int>> graph
= new Dictionary<int, List<int>>();
for (int i = 0; i <= n; i++)
{
graph[i] = new List<int>();
}
for (int i = 0; i < n - 1; i++)
{
graph[edges[i, 0]].Add(edges[i, 1]);
graph[edges[i, 1]].Add(edges[i, 0]);
}
Dictionary<int, int> freq = new Dictionary<int, int>();
int ans = DFS(0, V, 1, -1, 0, freq, graph);
return ans;
}
// Driver code
public static void Main()
{
int N = 5;
int[,] edges
= { { 1, 2 }, { 2, 4 }, { 2, 5 }, { 5, 3 } };
int[] V = { 7, 9, 9, 4, 8 };
// Function Call
Console.Write(FindTotalPath(N, edges, V));
}
}
// This code is contributed by Saurabh Jaiswal