#pragma GCC optimize("O3")
#pragma GCC target("avx2")
#include "circuit.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <vector>
constexpr int mod = 1e9 + 2022;
int add(int a, int b) {
return a + b - mod * (a + b >= mod);
}
int mul(int a, int b) {
return a * 1ULL * b % mod;
}
int n, m;
std::vector<int> prv;
std::vector<std::vector<int>> nxt;
std::vector<int> data;
std::vector<std::array<int, 2>> dp;
void count() {
for (int i = n - 1; i >= 0; i--) {
int all = 1, sum = 0;
for (int id = 0; id < nxt[i].size(); id++) {
int t = nxt[i][id];
int s = dp[t][0] + dp[t][1];
sum = add(mul(sum, s), mul(all, dp[t][1]));
all = mul(all, s);
}
all = mul(all, nxt[i].size());
dp[i] = {add(all, mod - sum), sum};
}
}
void init(int n, int m, std::vector<int> P, std::vector<int> A) {
::n = n;
::m = m;
data = A;
prv = P;
dp.resize(n + m);
for (int i = 0; i < m; i++) {
dp[n + i] = {data[i] == 0, data[i] == 1};
}
nxt.resize(n);
for (int i = 1; i < n + m; i++) {
nxt[prv[i]].push_back(i);
}
count();
}
int count_ways(int L, int R) {
L -= n;
R -= n;
R++;
for (int i = L; i < R; i++) {
data[i] ^= 1;
dp[n + i] = {data[i] == 0, data[i] == 1};
}
count();
return dp[0][1];
}