计蒜客42551

include

include

include

include

include

include

include

include

include

include

include

include

//#include

include

include

pragma GCC optimize(2)

define up(i,a,b) for(int i=a;i<b;i++)

define dw(i,a,b) for(int i=a;i>b;i--)

define upd(i,a,b) for(int i=a;i<=b;i++)

define dwd(i,a,b) for(int i=a;i>=b;i--)

//#define local
typedef long long ll;
typedef unsigned long long ull;
const double esp = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int inf = 1e9;
using namespace std;
ll read()
{
char ch = getchar(); ll x = 0, f = 1;
while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
typedef pair<int, int> pir;

define lson l,mid,root<<1

define rson mid+1,r,root<<1|1

define lrt root<<1

define rrt root<<1|1

const int N = 3e5 + 10;
int pos[N << 1], rk[N << 1];
char alph[N];
vectorvec[N], vec2[N << 1];
int n, q;
struct exsam {
int len[N << 1];
int par[N << 1];
int trans[N << 1][30];
int fa[N << 1][30];
ll tag[N << 1];
int tot = 1;
int work(int p, int c) {
int newq = ++tot; int q = trans[p][c];
len[newq] = len[p] + 1;
par[newq] = par[q]; memcpy(trans[newq], trans[q], sizeof(trans[q]));
par[q] = newq;
for (; p&&trans[p][c] == q; p = par[p]) {
trans[p][c] = newq;
}
return newq;
}
int ins(int p, int c) {
if (trans[p][c]) {
int q = trans[p][c];
if (len[p] + 1 == len[q]) {
return q;
}
else {
int tmp = work(p, c);
return tmp; }
}
else {
int now = ++tot;
len[now] = len[p] + 1;
for (; p && !trans[p][c]; p = par[p])
trans[p][c] = now;
if (!p) {
par[now] = 1;
}
else {
int q = trans[p][c];
if (len[q] == len[p] + 1)par[now] = q;
else par[now] = work(p, c);
}
return now;
}
}
void build(int u,int fa) {
pos[u] = ins(pos[fa], alph[u] - 'A');
tag[pos[u]]++;
rk[pos[u]] = u;
for (auto k : vec[u]) {
if (k == fa)continue;
build(k, u);
}
}
void build2() {
upd(i, 2, tot) {
vec2[par[i]].push_back(i);
}
dfs(1, 0);
}
ll dp[N << 1];
void dfs(int u, int f) {
fa[u][0] = f;
upd(i, 1, 21) {
fa[u][i] = fa[fa[u][i - 1]][i - 1];
}
dp[u] = tag[u];
for (auto k : vec2[u]) {
if (k == f)continue;
dfs(k, u);
dp[u] += dp[k];
}
}
ll query(int u, int x) {
u = pos[u];
dwd(i, 21, 0) {
if (len[fa[u][i]] >= x) {
u = fa[u][i];
}
}
return dp[u];
}
}S;
void addedge(int u, int v) {
vec[u].push_back(v);
vec[v].push_back(u);
}
int main() {
n = read(); q = read();
scanf("%s", alph + 1);
int u;
pos[0] = 1;
upd(i, 1, n-1) {
u = read();
addedge(u, i + 1);
}
S.build(1, 0);
S.build2();
int xi, li;
while (q--) {
xi = read(), li = read();
printf("%lld\n", S.query(xi, li));
}
return 0;
}

posted @ 2020-12-06 22:44  LORDXX  阅读(37)  评论(0编辑  收藏  举报