1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <cstdio> #include <vector> #define eb emplace_back using namespace std; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') if (c == '-') flag = true; x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; if (flag) x = ~x + 1; } template <class Type, class ...Rest> void read (Type &x, Rest &...y) { read(x), read(y...); } template <class Type> void write (Type x) { if (x < 0) putchar('-'), x = ~x + 1; if (x > 9) write(x / 10); putchar('0' + x % 10); } typedef long long LL; const int N = 5e4 + 10, mod = 201314; vector <int> g[N]; int n, m, ans[N], p[N], d[N], sz[N]; int son[N], top[N], stmp, dfn[N]; struct Query { int op, id, z; Query (int _op, int _id, int _z) : op(_op), id(_id), z(_z) { } }; vector <Query> q[N]; struct Node { LL s, t; } tr[N << 2]; void modify (int l, int r, int L = 1, int R = n, int x = 1) { tr[x].s += (min(r, R) - max(l, L) + 1); if (L >= l && R <= r) return void(++tr[x].t); int mid = L + R >> 1; if (l <= mid) modify(l, r, L, mid, x << 1); if (r > mid) modify(l, r, mid + 1, R, x << 1 | 1); } LL query (int l, int r, int L = 1, int R = n, int x = 1) { if (L >= l && R <= r) return tr[x].s; int mid = L + R >> 1; LL res = (min(r, R) - max(l, L) + 1) * tr[x].t; if (l <= mid) res += query(l, r, L, mid, x << 1); if (r > mid) res += query(l, r, mid + 1, R, x << 1 | 1); return res; } void dfs1 (int u) { sz[u] = 1; for (int v : g[u]) { d[v] = d[u] + 1; dfs1(v); sz[u] += sz[v]; if (sz[v] > sz[son[u]]) son[u] = v; } } void dfs2 (int u, int t) { top[u] = t; dfn[u] = ++stmp; if (!son[u]) return; dfs2(son[u], t); for (int v : g[u]) if (v ^ p[u] && v ^ son[u]) dfs2(v, v); } void modifyPath (int x) { for (; top[x] ^ 1; x = p[top[x]]) modify(dfn[top[x]], dfn[x]); modify(1, dfn[x]); } LL queryPath (int x) { LL res = 0; for (; top[x] ^ 1; x = p[top[x]]) res += query(dfn[top[x]], dfn[x]); res += query(1, dfn[x]); return res; } int main () { read(n, m); for (int i = 2; i <= n; ++i) read(p[i]), g[++p[i]].eb(i); dfs1(1), dfs2(1, 1); for (int i = 1, l, r, z; i <= m; ++i) { read(l, r, z), ++l, ++r, ++z; q[l - 1].eb(-1, i, z), q[r].eb(1, i, z); } for (int i = 1; i <= n; ++i) { modifyPath(i); for (Query j : q[i]) ans[j.id] += j.op * queryPath(j.z); } for (int i = 1; i <= m; ++i) write(ans[i] % mod), puts(""); return 0; }
|