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 nn companies in the city. The ii-th company has mim_i people.

A company can be represented by a tree rooted at 11. Initially, node 11 is the boss. The children of a node are its subordinates, and the parent of a node is its supervisor. The size of the ii-th tree is mim_i, with nodes numbered from 11 to mim_i.

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 xx in the 11-st tree, and ljs is node yy in the 22-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 11. 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 11 knows 22 and 22 knows 33, then the relationship between 11 and 33 is 22.

Input Format

The first line contains an integer nn, representing the number of companies.

Lines 22 to n+1n+1: in line i+1i+1, the first integer is mim_i, representing the number of people in the ii-th company. Then there are mi1m_i - 1 integers; the jj-th number represents the supervisor of node j+1j+1 in this tree.

Line n+2n+2 contains two integers xx and yy, meaning myz is node xx in the 11-st tree, and ljs is node yy in the 22-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 88.

Constraints

This problem uses bundled testdata.

subtask ID nn\leq m\sum m \leq Special case Score
11 22 10310^3 None 2020
22 10510^5 10610^6 x=1x = 1, y=1y = 1
33 All trees are random trees
44 None 4040

Random tree generation rule: for node ii (2im2 \le i \le m), its supervisor is chosen uniformly at random from 11 to i1i - 1.

For 100%100\% of the testdata, 2n1052 \leq n \leq 10^5, 1mi1 \le m_i, m106\sum m \leq 10^6, 1xm11 \leq x \leq m_1, 1ym21 \leq y \leq m_2.

Translated by ChatGPT 5