#P9437. 『XYGOI round1』一棵树

    ID: 10384 远端评测题 1000ms 512MiB 尝试: 0 已通过: 0 难度: 6 上传者: 标签>动态规划 DPO2优化树形 DP洛谷月赛

『XYGOI round1』一棵树

Background

Java brought a tree to the problem-setting group today, but the unreasonable MX took it for himself.

Problem Description

MX has a tree with nn nodes, and each node has a number aia_i on it.

Define the weight w(x,y)w(x,y) of a path (x,y)(x,y) as the number obtained by writing down, in order, all the numbers on the nodes along the shortest path from xx to yy. For example, if the path passes through four nodes labeled with numbers 3,21,0,53,21,0,5 in this order, then the weight of this path is 3210532105.

MX wants to know the sum of the weights of all paths in this tree, i.e., x=1ny=1nw(x,y)\sum\limits_{x=1}^n\sum\limits_{y=1}^nw(x,y).

The answer may be very large. Output it modulo 998244353998244353.

Input Format

The first line contains a positive integer nn.

The second line contains nn non-negative integers aia_i.

The third line contains n1n-1 positive integers. The ii-th number pip_i indicates that there is an edge between node pip_i and node i+1i+1. It is guaranteed that 1pii1\le p_i\le i.

Output Format

Output one integer in a single line, representing the answer modulo 998244353998244353.

3
1 2 3
1 2
538
3
5 21 0
1 2
6418
4
1 2 3 4
1 2 2

1900
6
10 23 16 3 125 1
1 1 1 1 1

7680868

Hint

Sample Explanation

Explanation for sample 1: 1+12+123+2+21+23+3+32+321=5381+12+123+2+21+23+3+32+321=538.

Explanation for sample 2: 5+521+5210+21+215+210+0+021+0215=64185+521+5210+21+215+210+0+021+0215=6418.

Constraints

This problem uses bundled testdata.

Let V=max{ai}+1V=\max\{a_i\}+1.

Subtask Points nn\le VV\le Special Properties
0 5 10001000 1010
1 15 80008000 10910^9
2 10610^6 pi=ip_i=i
3 pi=1p_i=1
4 50

For 100%100\% of the testdata, 1n1061\le n\le 10^6 and 0ai<1090\le a_i<10^9.

Translated by ChatGPT 5