Tree Recreation

3.1

7 votes
Graphs, Depth-first search, Medium, Algorithms, Depth First Search
Problem

You are given a tree consisting of N vertices, rooted at vertex 1. Each vertex consists of a lowercase English alphabet as a node value.

If the ancestor node has the same node value as that of any vertex, then that ancestor node is considered as its valid parent vertex.

Your task is to detach all the nodes from the tree and attach them to any of the valid parent vertices (in the initial tree) and print the number of connected components obtained.

Input format

  • First line: An integer T denoting the number of test cases
  • Next line: An integer N denoting the number of nodes in the tree
  • Next line: N lowercase English alphabets such as Val1, Val2 , Val3 ....ValN, where Vali denotes the node value of the ith node
  • Next N-1 lines: Two integers Ui and  Vi  representing an edge between the nodes Ui and Vi

Output format

For each test case, print a single integer M in a new line representing the number of connected components formed after recreating the tree.

Constraints

1T10

1N105

aValiz

1Ui,ViN,Ui!=Vi

  • It is guaranteed that the given input forms a tree.
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

Node 4 can be connected to Node 1.

Node 3 has no ancestors with the same value, thus no parent.

2 components : {1, 2, 4}, {3}

Editor Image

?