luogu#P5043. 【模板】树同构 / [BJOI2015] 树的同构

    ID: 3833 远端评测题 1000ms 250MiB 尝试: 0 已通过: 0 难度: 7 上传者: 标签>图论2015各省省选北京哈希 hashing

【模板】树同构 / [BJOI2015] 树的同构

Problem Description

A tree is a very common data structure.

We call a connected undirected graph with NN vertices and N1N - 1 edges a tree.

If we choose a vertex as the root and traverse from the root, then every other vertex has a predecessor. This tree becomes a rooted tree.

For two trees T1T_1 and T2T_2, if we can relabel all vertices of T1T_1 so that T1T_1 and T2T_2 become exactly the same, then these two trees are isomorphic. That is, they have the same shape.

Now you are given MM unrooted trees. Please partition them into several equivalence classes according to the isomorphism relation.

Input Format

The first line contains an integer MM.

The next MM lines each contain several integers describing one tree. The first integer is NN, the number of vertices. Then follow NN integers, which in order give the parent vertex number of each vertex numbered from 11 to NN. The parent number of the root vertex is 00.

Output Format

Output MM lines. Each line contains one integer, representing the smallest index among the trees that are isomorphic to the corresponding tree.

4 
4 0 1 1 2 
4 2 0 2 3 
4 0 1 1 1 
4 0 1 2 3 
1 
1 
3 
1 

Hint

Trees numbered 11, 22, and 44 are isomorphic. The tree numbered 33 is only isomorphic to itself.

For 100%100\% of the testdata, it is guaranteed that 1N,M501 \leq N, M \leq 50.

Translated by ChatGPT 5