이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
vector<int> adj[300005], reg[25005], regst[25005], calc[25005];
int st[300005], en[300005], timer = 0;
void dfs(int i, int p) {
st[i] = timer;
timer++;
for (int j : adj[i]) {
if (j == p) {
continue;
}
dfs(j, i);
}
en[i] = timer;
}
void solve() {
int n, r, q;
cin >> n >> r >> q;
for (int i = 1; i <= n; i++) {
int s, h;
if (i == 1) {
cin >> h;
reg[h].push_back(i);
} else {
cin >> s >> h;
reg[h].push_back(i);
adj[s].push_back(i);
adj[i].push_back(s);
}
}
dfs(1, -1);
for (int i = 1; i <= r; i++) {
for (int j : reg[i]) {
regst[i].push_back(st[j]);
}
sort(regst[i].begin(), regst[i].end());
}
for (int a = 1; a <= r; a++) {
if (reg[a].size() > 450) {
calc[a].resize(r+1, 0);
for (int b = 1; b <= r; b++) {
if (a == b) {
continue;
}
for (int i : reg[a]) {
int l, r;
l = upper_bound(regst[b].begin(), regst[b].end(), st[i]) - regst[b].begin();
r = lower_bound(regst[b].begin(), regst[b].end(), en[i]) - regst[b].begin();
calc[a][b] += r-l;
}
}
}
}
while(q--) {
int a, b, ans = 0;
cin >> a >> b;
if (reg[a].size() <= 450) {
for (int i : reg[a]) {
int l, r;
l = upper_bound(regst[b].begin(), regst[b].end(), st[i]) - regst[b].begin();
r = lower_bound(regst[b].begin(), regst[b].end(), en[i]) - regst[b].begin();
ans += r-l;
}
} else {
ans += calc[a][b];
}
cout << ans << endl;
}
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
t = 1;
while(t--) {
solve();
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |