#P9648. [SNCPC2019] Unrooted Trie

[SNCPC2019] Unrooted Trie

题目描述

Recall the definition of a trie:

  • A trie of size nn is a rooted tree with nn vertices and (n1)(n-1) edges, where each edge is marked with a character;
  • Each vertex in a trie represents a string. Let s(x)s(x) be the string vertex xx represents;
  • The root of the trie represents an empty string. Let vertex uu be the parent of vertex vv, and let cc be the character marked on the edge connecting vertex uu and vv, we have s(v)s(v) = s(u)+cs(u) + c. 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 nn vertices and (n1)(n-1) 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 TT, indicating the number of test cases. For each test case:

The first line contains an integer nn (1n1051 \le n \le 10^5), indicating the size of the tree.

For the following (n1)(n-1) lines, the ii-th line contains two integers uiu_i, viv_i (1ui,vin1 \le u_i, v_i \le n) and a character cic_i separated by a space, indicating that there is an edge marked with a character cic_i connecting vertex uiu_i and viv_i. It's guaranteed that cic_i will only be lower-case English letters.

It's guaranteed that the given graph is a tree, and the sum of nn of all test cases will not exceed 10610^6.

输出格式

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 的定义是这样的:

  • 一棵大小为 nn 的 trie,是一棵有着 nn 个节点和 (n1)(n-1) 条边的有根树,每一条边上都标有一个字符;

  • 在 trie 中,从根结点到树上某一结点的路径代表一个字符串,节点 xx 代表的字符串记为 s(x)s(x),特别地,根节点代表的字符串为空串。

  • 若节点 uu 是节点 vv 的父节点,且 cc 是连接 uuvv 的边上的字符,则有 s(v)=s(u)+cs(v) = s(u) + c(这里的 ++ 表示字符串的连接,而非普通的加法运算)。

当每一个节点代表的字符串互不相同时,该 trie 是合法的。

题目描述

给出一个无根的 trie,求其中有多少节点可作为该 trie 的根,使得该 trie 合法。

输入格式

每个测试点由多组数据组成。

输入的第一行包含一个正整数 TT,代表测试数据的组数。

对于每组测试数据:

数据的第一行包含一个正整数 nn,代表 trie 的大小。

接下来的 (n1)(n-1) 行中,第 ii 行包含两个正整数 ui,viu_i,v_i 以及一个字符 cic_i,用空格隔开,表示有一条标有 cic_i 的边连接着 uiu_iviv_i

输出格式

对于每组测试数据,输出一行一个正整数,表示可以成为根后可以使该 trie 合法的节点的个数。

说明/提示

【样例解释】

对于第一组测试数据,只能选择节点 11 或节点 22 作为根,否则 s(1)s(1)s(2)s(2) 相同。

对于第二组测试数据,无论如何选择节点作为根,s(1)s(1)s(2)s(2)s(5)s(5)s(6)s(6) 相同。

【数据范围】

对于每组数据,1n2×1051 \le n \le 2 \times 10^51ui,vin1 \le u_i,v_i \le ncic_i 都是小写字母。

对于每个测试点,保证给出的图是一棵树,所有的 nn 之和不会超过 10610^6

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 s(1)s(1) and s(2)s(2) will be the same.

For the second sample test case, no matter which vertex we select as the root, s(1)s(1) and s(2)s(2), or s(5)s(5) and s(6)s(6) will be the same.