思路:建树->对树进行更新维护->输出
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <algorithm> using namespace std; #define rep(i, s, t) for(int i = (s); i <= (t); i++) #define dwn(i, s, t) for(int i = (s); i >= (t); i--) int read() { int x = 0, f = 1; char c = getchar(); while(!isdigit(c)){ if(c == '-') f = -1; c = getchar(); } while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); } return x * f; } #define maxn 100010 #define MOD 19260817 #define LL long long int n, q, fa[maxn], m, head[maxn], nxt[maxn], to[maxn]; void AddEdge(int a, int b) { to[++m] = b; nxt[m] = head[a]; head[a] = m; return ; } int bel[maxn], siz[maxn], add[maxn], sum[maxn], indi[maxn]; void build(int u) { for(int e = head[u]; e; e = nxt[e]) if(to[e] != fa[u]) bel[to[e]] = u, siz[u]++, build(to[e]); return ; } int main() { n = read(); q = read(); rep(i, 2, n) fa[i] = read(), AddEdge(fa[i], i); bel[1] = 0; siz[0] = 1; build(1); int Ans = 0; rep(i, 1, q) { int x = read(); sum[x] += siz[x]; if(sum[x] >= MOD) sum[x] -= MOD; add[x]++; indi[x]++; sum[bel[x]]++; if(sum[bel[x]] >= MOD) sum[bel[x]] -= MOD; if(fa[x]) { indi[fa[x]]++; sum[bel[fa[x]]]++; if(sum[bel[fa[x]]] >= MOD) sum[bel[fa[x]]] -= MOD; } int nowans = (sum[x] + indi[x] + add[bel[x]]) % MOD; if(fa[x]) (nowans += indi[fa[x]] + add[bel[fa[x]]]) %= MOD; Ans += (LL)nowans * i % MOD; if(Ans >= MOD) Ans -= MOD; } printf("%d\n", Ans); return 0; }