#P9648. [SNCPC2019] Unrooted Trie
[SNCPC2019] Unrooted Trie
题目描述
Recall the definition of a trie:
- A trie of size is a rooted tree with vertices and edges, where each edge is marked with a character;
- Each vertex in a trie represents a string. Let be the string vertex represents;
- The root of the trie represents an empty string. Let vertex be the parent of vertex , and let be the character marked on the edge connecting vertex and , we have = . Here indicates string concatenation, not the normal addition operation.
We say a trie is valid, if the string each vertex represents is distinct.
Given an unrooted tree with vertices and edges, where each edge is marked with a character, how many different vertices can be selected as the root of the tree so that the tree becomes a valid trie?
输入格式
There are multiple test cases. The first line of the input contains an integer , indicating the number of test cases. For each test case:
The first line contains an integer (), indicating the size of the tree.
For the following lines, the -th line contains two integers , () and a character separated by a space, indicating that there is an edge marked with a character connecting vertex and . It's guaranteed that will only be lower-case English letters.
It's guaranteed that the given graph is a tree, and the sum of of all test cases will not exceed .
输出格式
For each test case output one line containing one integer, indicating the number of different vertices that can be selected as the root of the tree to make it a valid trie.
题目大意
题目背景
trie 的定义是这样的:
-
一棵大小为 的 trie,是一棵有着 个节点和 条边的有根树,每一条边上都标有一个字符;
-
在 trie 中,从根结点到树上某一结点的路径代表一个字符串,节点 代表的字符串记为 ,特别地,根节点代表的字符串为空串。
-
若节点 是节点 的父节点,且 是连接 与 的边上的字符,则有 (这里的 表示字符串的连接,而非普通的加法运算)。
当每一个节点代表的字符串互不相同时,该 trie 是合法的。
题目描述
给出一个无根的 trie,求其中有多少节点可作为该 trie 的根,使得该 trie 合法。
输入格式
每个测试点由多组数据组成。
输入的第一行包含一个正整数 ,代表测试数据的组数。
对于每组测试数据:
数据的第一行包含一个正整数 ,代表 trie 的大小。
接下来的 行中,第 行包含两个正整数 以及一个字符 ,用空格隔开,表示有一条标有 的边连接着 和 。
输出格式
对于每组测试数据,输出一行一个正整数,表示可以成为根后可以使该 trie 合法的节点的个数。
说明/提示
【样例解释】
对于第一组测试数据,只能选择节点 或节点 作为根,否则 和 相同。
对于第二组测试数据,无论如何选择节点作为根, 和 或 和 相同。
【数据范围】
对于每组数据,,, 都是小写字母。
对于每个测试点,保证给出的图是一棵树,所有的 之和不会超过 。
2
6
3 1 a
3 2 a
3 4 b
4 5 c
4 6 d
6
3 1 a
3 2 a
3 4 b
5 4 c
6 4 c
2
0
提示
For the first sample test case, we can only select vertex 1 or vertex 2 as the root, otherwise and will be the same.
For the second sample test case, no matter which vertex we select as the root, and , or and will be the same.