#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
#define N 200020
#define M 200020
int fst[N], nxt[M], vv[M], e;
void init() {
memset(fst, -1, sizeof fst);
e = 0;
}
void add(int u, int v) {
vv[e] = v, nxt[e] = fst[u], fst[u] = e++;
}
int p[N], c[N];
int n;
int f[N];
int rt[N];
int ch[N*20][2], s[N*20], sz;
#define md (ll + rr >> 1)
int update(int i, int x, int v, int ll, int rr) {
int k = ++sz;
ch[k][0] = ch[i][0], ch[k][1] = ch[i][1];
if(ll == rr) {
s[k] = v;
return k;
}
if(x <= md) ch[k][0] = update(ch[i][0], x, v, ll, md);
else ch[k][1] = update(ch[i][1], x, v, md + 1, rr);
return k;
}
int query(int i, int x, int ll, int rr) {
if(ll == rr) return s[i];
if(x <= md) return query(ch[i][0], x, ll, md);
else return query(ch[i][1], x, md + 1, rr);
}
void build() {
queue<int> q;
q.push(0);
f[0] = 0;
while(!q.empty()) {
int u = q.front(); q.pop();
for(int i = fst[u]; ~i; i = nxt[i]) {
int v = vv[i];
f[v] = query(rt[f[u]], c[v], 1, n);
q.push(v);
}
rt[u] = rt[f[u]];
for(int i = fst[u]; ~i; i = nxt[i]) {
int v = vv[i];
rt[u] = update(rt[u], c[v], v, 1, n);
}
}
}
int main() {
scanf("%d", &n);
init();
for(int i = 1; i <= n; ++i) {
scanf("%d", &p[i]);
add(p[i], i);
}
for(int i = 1; i <= n; ++i) scanf("%d", &c[i]);
build();
for(int i = 1; i <= n; ++i) printf("%d%c", f[i], i == n? '\n': ' ');
return 0;
}
ICPCCamp 2016 Day 1 - A Aho-Corasick Automaton (主席树)
最新推荐文章于 2017-05-01 01:54:19 发布