This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
template<class T, class U>
void ckmin(T &a, U b)
{
if (a > b) a = b;
}
template<class T, class U>
void ckmax(T &a, U b)
{
if (a < b) a = b;
}
#define MP make_pair
#define PB push_back
#define LB lower_bound
#define UB upper_bound
#define fi first
#define se second
#define SZ(x) ((int) (x).size())
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, a, b) for (auto i = (a); i < (b); i++)
#define FORD(i, a, b) for (auto i = (a) - 1; i >= (b); i--)
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vpi;
typedef vector<pll> vpl;
const int MAXN = 200013;
int N, M, Q, T, K;
int parent[MAXN], arr[MAXN];
vi edge[MAXN];
int st[MAXN], ft[MAXN], loc[MAXN];
int ord[MAXN];
vi inds[MAXN], del[MAXN];
map<int, int> ans[MAXN];
void dfs(int u)
{
st[u] = T;
ft[u] = T;
ord[T] = u;
T++;
inds[arr[u]].PB(st[u]);
// cerr << "inds " << arr[u] << " PB " << st[u] << endl;
for (int v : edge[u])
{
dfs(v);
ft[u] = ft[v];
}
del[arr[u]].PB(ft[u]);
}
int order_of_key(vi &x, int n) //counts how many are strictly less than n.
{
return LB(ALL(x), n) - x.begin();
}
int32_t main()
{
cout << fixed << setprecision(12);
cerr << fixed << setprecision(4);
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> N >> M >> Q;
FOR(i, 0, N)
{
if (i)
{
cin >> parent[i];
parent[i]--;
edge[parent[i]].PB(i);
}
cin >> arr[i]; arr[i]--;
}
dfs(0);
while(Q--)
{
int x, y;
cin >> x >> y; x--; y--;
if (!ans[x].count(y))
{
//well shit.
int res = 0;
if (SZ(inds[x]) > SZ(inds[y]))
{
//for each node in y, count how many are in its parenthood.
for (int c : inds[y])
{
res += order_of_key(inds[x], c + 1) - order_of_key(del[x], c);
}
}
else
{
//for each node in x, count how many y's are in its subtree.
for (int c : inds[x])
{
int u = ord[c];
// cerr << "u = " << u << endl;
res += order_of_key(inds[y], ft[u] + 1) - order_of_key(inds[y], st[u]);
// cerr << "res from " << u << " = " << ft[u] + 1 << ' ' << st[u] << endl;
}
}
ans[x][y] = res;
}
cout << ans[x][y] << '\n';
fflush(stdout);
//how many are in subtree of some node of x.
//x is smaller.
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |