#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include "circuit.h"
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define sz(a) (int)a.size()
#define all(a) begin(a), end(a)
using vi = vector<int>;
using ll = long long;
using ar2 = array<ll,2>;
const int mxN = (int)5e3+10;
const int MOD = 1000002022;
int n, m;
vi a, p;
vi adj[mxN];
vector<ll> dp[mxN][2];
ar2 dfs(int s, int p){
if(sz(adj[s])==0){
if(a[s-n]==1) return {0,1};
return {1,0};
}
vector<ar2> v; v.clear();
for(auto u : adj[s]){
if(u==p) continue;
v.pb(dfs(u,s));
}
int k = sz(v);
dp[s][0].clear(), dp[s][1].clear();
dp[s][0].resize(k+1,0);
dp[s][1].resize(k+1,0);
vector<vector<ll>> num(k+1,vector<ll>(k+1,0));
num[0][0] = 1;
for(int i = 1; i <= k; i++){
for(int j = 0; j <= k; j++){
num[i][j]+=(num[i-1][j]*v[i-1][0])%MOD, num[i][j]%=MOD;
if(j) num[i][j]+=(num[i-1][j-1]*v[i-1][1])%MOD, num[i][j]%=MOD;
}
}
for(int i = 1; i <= k; i++)
num[k][i]+=num[k][i-1];
for(int i = 1; i <= k; i++){
dp[s][0][i]+=num[k][i-1];
dp[s][1][i]+=num[k][k]-num[k][i-1];
for(int j:{0,1}) dp[s][j][i]%=MOD;
}
int num0 = 0, num1 = 0;
for(int i = 1; i <= k; i++){
num0+=dp[s][0][i], num1+=dp[s][1][i];
num0%=MOD, num1%=MOD;
}
return {num0, num1};
}
void init(int N, int M, vi P, vi A) {
n = N, m = M;
for(auto u : P) p.pb(u);
for(auto u : A) a.pb(u);
for(int i = 1; i < n+m; i++)
adj[p[i]].pb(i);
}
int count_ways(int L, int R) {
for(int i = L; i <= R; i++) a[i-n]^=1;
return dfs(0,-1)[1];
}