luogu#P9663. [ICPC2021 Macao R] Permutation on Tree

    ID: 13632 远端评测题 1000ms 512MiB 尝试: 0 已通过: 0 难度: 6 上传者: 标签>动态规划,dp2021O2优化树形 dpICPC澳门

[ICPC2021 Macao R] Permutation on Tree

题目描述

Given a tree with nn vertices where vertex rr is the root, we say a permutation p1,p2,,pnp_1, p_2, \cdots, p_n of nn is good if it satisfies the following constraint:

  • Let axa_x be the index of xx in the permutation (That is, pax=xp_{a_x} = x). For all 1u,vn1 \le u, v \le n, if vertex uu is an ancestor of vertex vv in the tree, then au<ava_u < a_v.

Define the score of a permutation to be i=1n1pipi+1\sum\limits_{i=1}^{n-1} |p_i - p_{i+1}| where x|x| is the absolute value of xx. Calculate the sum of scores of all different good permutations.

输入格式

There is only one test case in each test file.

The first line contains two integers nn and rr (2n2002 \le n \le 200, 1rn1 \le r \le n) indicating the size of the tree and the root.

For the following (n1)(n - 1) lines, the ii-th line contains two integers uiu_i and viv_i (1ui,vin1 \le u_i, v_i \le n) indicating an edge connecting vertex uiu_i and viv_i in the tree.

输出格式

For each test case output one line containing one integer indicating the sum of scores of all different good permutations. As the answer may be large, output the answer modulo (109+7)(10^9 + 7).

题目大意

【题目描述】

给定一个有 nn 个顶点的树,其中顶点 rr 是根,如果一个排列 p1,p2,,pnp_1, p_2, \cdots, p_n 满足以下约束条件,我们称其为好排列:

  • axa_x 是排列中 xx 的索引(即 pax=xp_{a_x} = x)。对于所有 1u,vn1 \le u, v \le n,如果顶点 uu 是树中顶点 vv 的祖先,则 au<ava_u < a_v

定义排列的分数为 i=1n1pipi+1\sum\limits_{i=1}^{n-1} |p_i - p_{i+1}|,其中 x|x| 表示 xx 的绝对值。计算所有不同好排列的分数之和。

【输入格式】

每个测试文件中包含一个测试用例。输入的第一行包含两个整数 nnrr (2n2002 \le n \le 200, 1rn1 \le r \le n),表示树的大小和根。

接下来的 (n1)(n - 1) 行,第 ii 行包含两个整数 uiu_iviv_i (1ui,vin1 \le u_i, v_i \le n),表示树中连接顶点 uiu_iviv_i 的边。

【输出格式】

对于每个测试用例,输出一行,包含一个整数,表示所有不同好排列的分数之和。由于答案可能很大,输出答案对 (109+7)(10^9 + 7) 取模的结果。

【样例解释】

对于第一个样例测试用例,有三个好排列:{2,1,3,4}\{2, 1, 3, 4\}{2,1,4,3}\{2, 1, 4, 3\}{2,3,1,4}\{2, 3, 1, 4\}。它们的分数分别为 445566,因此答案为 4+5+6=154 + 5 + 6 = 15

对于第二个样例测试用例,只有一个好排列:{1,2,3}\{1, 2, 3\}。它的分数为 22

翻译来自于:ChatGPT

4 2
1 2
2 3
1 4
15
3 1
1 2
2 3
2

提示

For the first sample test case, there are three good permutations: {2,1,3,4}\{2, 1, 3, 4\}, {2,1,4,3}\{2, 1, 4, 3\} and {2,3,1,4}\{2, 3, 1, 4\}. Their scores are 44, 55 and 66 respectively so the answer is 4+5+6=154 + 5 + 6 = 15.

For the second sample test case, there is only one good permutation: {1,2,3}\{1, 2, 3\}. It's score is 22.