luogu#P10406. 「SMOI-R1」Company
「SMOI-R1」Company
Background
LAR got fired by the boss, and everything below is his dream.
Problem Description
There are companies in the city. The -th company has people.
A company can be represented by a tree rooted at . Initially, node is the boss. The children of a node are its subordinates, and the parent of a node is its supervisor. The size of the -th tree is , with nodes numbered from to .
There are too many companies, and it is troublesome for the government to manage them, so the government wants LAR to merge these companies. To merge two companies, one person in one company who initially has no subordinates (an employee or the boss) becomes the supervisor of the current boss of the other company. After the merge is completed, the two companies become one company.
Only two people who are supervisor and subordinate of each other know each other.
myz is node in the -st tree, and ljs is node in the -nd tree. Because myz and ljs have very incompatible personalities (they do not know each other), LAR wants their relationship to be as far as possible.
The distance between two people who know each other is . The relationship between two people is defined as the shortest distance between them in the social network (you can simply treat it as the shortest distance between the two nodes in the final tree). For example, if knows and knows , then the relationship between and is .
Input Format
The first line contains an integer , representing the number of companies.
Lines to : in line , the first integer is , representing the number of people in the -th company. Then there are integers; the -th number represents the supervisor of node in this tree.
Line contains two integers and , meaning myz is node in the -st tree, and ljs is node in the -nd tree.
Output Format
Output one integer, representing the maximum possible relationship value between myz and ljs.
3
3 1 1
3 1 2
4 1 2 1
2 3
8
Hint
Sample Explanation
Before any merge operations, the companies in the city are as follows (the number in parentheses is the company where the node belongs initially):

To maximize the relationship value, the final company can be formed as shown below:

The answer is .
Constraints
This problem uses bundled testdata.
| subtask ID | Special case | Score | ||
|---|---|---|---|---|
| None | ||||
| , | ||||
| All trees are random trees | ||||
| None |
Random tree generation rule: for node (), its supervisor is chosen uniformly at random from to .
For of the testdata, , , , , .
Translated by ChatGPT 5