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 106 107 108 109 110 111 112 113 114 115 116 117
| #include <cstdio> #include <set> #include <map> #include <string> #include <vector> #include <iostream> using namespace std; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') 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(x % 10 + '0'); } const int N = 1e5 + 10, M = 2e6 + 10;; int n, m, w[N], d[N], ans[N]; vector <int> g[N]; int tot; map <string, int> h; int id (string s) { if (!h.count(s)) h[s] = ++tot; return h[s]; } void dfs1 (int x) { for (int i : g[x]) d[i] = d[x] + 1, dfs1(i); } struct Node { int l, r; set <int> s; } tr[M]; int idx, rt[N]; struct Query { int k, id; }; vector <Query> q[N]; void pushup (int x) { int a = tr[x].l, b = tr[x].r; if (tr[a].s.size() < tr[b].s.size()) swap(a, b); tr[x].s = tr[a].s; for (int i : tr[b].s) tr[x].s.insert(i); } void modify (int &x, int t, int k, int l = 1, int r = n) { if (!x) x = ++idx; if (l == r) return void(tr[x].s.insert(k)); int mid = l + r >> 1; t <= mid ? modify(tr[x].l, t, k, l, mid) : modify(tr[x].r, t, k, mid + 1, r); pushup(x); } int merge (int x, int y, int l = 1, int r = n) { if (!x || !y) return x | y; if (l == r) { if (tr[x].s.size() < tr[y].s.size()) swap(x, y); for (int i : tr[y].s) tr[x].s.insert(i); tr[y].s.clear(); return x; } int mid = l + r >> 1; tr[x].l = merge(tr[x].l, tr[y].l, l, mid); tr[x].r = merge(tr[x].r, tr[y].r, mid + 1, r); return x; } int query (int x, int t, int l = 1, int r = n) { if (!x || t > r) return 0; if (l == r) return tr[x].s.size(); int mid = l + r >> 1; return t <= mid ? query(tr[x].l, t, l, mid) : query(tr[x].r, t, mid + 1, r); } void dfs2 (int x) { modify(rt[x] = ++idx, d[x], w[x]); for (int i : g[x]) dfs2(i), merge(rt[x], rt[i]); for (Query i : q[x]) ans[i.id] = query(rt[x], i.k); } int main () { read(n); for (int i = 1, a; i <= n; ++i) { string s; cin >> s; w[i] = id(s); read(a), g[a].push_back(i); } dfs1(0); read(m); for (int i = 1, x, k; i <= m; ++i) { read(x, k); q[x].push_back((Query){d[x] + k, i}); } dfs2(0); for (int i = 1; i <= m; ++i) write(ans[i]), puts(""); return 0; }
|