Words And Trees
Practice
4.1 (33 votes)
Algorithms
Depth first search
Easy
Graphs
Trees
Problem
78% Success 4578 Attempts 20 Points 1s Time Limit 256MB Memory 1024 KB Max Code

You are given a rooted tree with N nodes. Each node contains a lowercase English letter. Node with label 1 is the root.There are Q questions of the form

X S: Here X is the root of subtree and S is a string.

For each question, let T be the string built using all the characters in the nodes of subtree with root X (each subtree node character comes exactly once) .
For each question, print minimum number of characters to be added to T , so that the we can build S using some characters of string T (each character of string T can be used at most once).


Hint: Find all the characters coming in each subtree and use it to get the answer to each question.

Input Format

The first line of input consists of two space separated integers N and Q that are number of nodes in the tree and number of questions respectively.
Next line will contain N space separated lowercase English letters, where \(i^{th}\) letter will be the letter stored in node with label i .
Each of the next \(N-1\) lines contains two space separated integers u and v that denote there is an edge between nodes with labels u and v .
Next Q lines follow. Each line will contain an integer X that denotes the node label and a string S separated by a single space.

Output Format

For each query, print the required answer in a new line.

Input Constraints

\(2 \le N \le 10^5\)

\(1 \le Q \le 10^5\)

\(1 \le u,v \le N ; u!=v\)

\(1\le X \le N\)

All characters in nodes and string are lowercase English letters.

Sum of lengths of strings in all the questions is at most \(10^6\)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:20
37 votes
Tags:
AlgorithmsApprovedBacktrackingDepth First SearchEasyGraphsOpenRecursion
Points:20
20 votes
Tags:
AlgorithmsDepth First SearchEasyGraphs
Points:20
41 votes
Tags:
AlgorithmsC++Depth First SearchGraphs