题目收集
题目列表题单
返回列表

DeadLine

CodeforcesP0071· 1000ms· 1024 MB· ZJU Summer 2026 Contest 7原题链接
数学dp

创建于 2026/07/18 · 更新于 2026/07/18

题目描述

There are nnn states numbered 1,2,…,n1,2,\ldots,n1,2,…,n. Initially, the process is at state 111.

Each operation increases the number of performed operations by 111, and then the next state is determined as follows:

  • If the current state is 111, the process always moves to state 222 after the operation.
  • If the current state is nnn, the process terminates after the operation.
  • For each state iii such that 2≤i≤n−12\le i\le n-12≤i≤n−1, two values AiA_iAi​ and PiP_iPi​ are associated with it. After an operation at state iii, the process moves to state i+1i+1i+1 with probability PiP_iPi​, and moves to state AiA_iAi​ with probability 1−Pi1-P_i1−Pi​. It is guaranteed that 1≤Ai<i1\le A_i \lt i1≤Ai​<i.

For a fixed sequence of probabilities P2,P3,…,Pn−1P_2,P_3,\ldots,P_{n-1}P2​,P3​,…,Pn−1​, let f(P2,P3,…,Pn−1)f(P_2,P_3,\ldots,P_{n-1})f(P2​,P3​,…,Pn−1​) be the expected number of operations needed until the process terminates, starting from state 111.

You are given an array of length n−2n-2n−2: P1′,P2′,…,Pn−2′.P'_1,P'_2,\ldots,P'_{n-2}.P1′​,P2′​,…,Pn−2′​. A permutation ppp of length n−2n-2n−2 is chosen uniformly at random. Then the probabilities of the internal states are assigned by Pi+1=Ppi′(1≤i≤n−2).P_{i+1}=P'_{p_i} (1\le i\le n-2).Pi+1​=Ppi​′​(1≤i≤n−2).

If several values in P′P'P′ are equal, they are still treated as different elements according to their indices. In other words, all permutations of indices are counted separately.

Your task is to compute 1(n−2)!∑p∈Sn−2f(Pp1′,Pp2′,…,Ppn−2′)(mod998244353).\frac{1}{(n-2)!}\sum_{p\in S_{n-2}} f(P'_{p_1},P'_{p_2},\ldots,P'_{p_{n-2}}) \pmod {998244353}.(n−2)!1​∑p∈Sn−2​​f(Pp1​′​,Pp2​′​,…,Ppn−2​′​)(mod998244353).

输入格式

The first line contains one integer nnn (2≤n≤50002\le n\le 50002≤n≤5000).

The second line contains n−2n-2n−2 integers A2,A3,…,An−1A_2,A_3,\ldots,A_{n-1}A2​,A3​,…,An−1​ (1≤Ai<i1\le A_i \lt i1≤Ai​<i).

The third line contains n−2n-2n−2 integers P1′,P2′,…,Pn−2′P'_1,P'_2,\ldots,P'_{n-2}P1′​,P2′​,…,Pn−2′​ (2≤Pi′<9982443532\le P'_i \lt 9982443532≤Pi′​<998244353), denoting the probabilities modulo 998244353998244353998244353.

输出格式

The first line contains one integer nnn (2≤n≤50002\le n\le 50002≤n≤5000).

The second line contains n−2n-2n−2 integers A2,A3,…,An−1A_2,A_3,\ldots,A_{n-1}A2​,A3​,…,An−1​ (1≤Ai<i1\le A_i \lt i1≤Ai​<i).

The third line contains n−2n-2n−2 integers P1′,P2′,…,Pn−2′P'_1,P'_2,\ldots,P'_{n-2}P1′​,P2′​,…,Pn−2′​ (2≤Pi′<9982443532\le P'_i \lt 9982443532≤Pi′​<998244353), denoting the probabilities modulo 998244353998244353998244353.

样例输入 #1

4
1 1
499122177 499122177

样例输出 #1

11

样例输入 #2

10
1 2 3 1 4 2 1 3
862701445 502573809 116853317 997064101 523218672 483172097 719515549 37526840

样例输出 #2

374531687