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>
#define FOR(i, x, y) for (int i = x; i < y; i++)
typedef long long ll;
using namespace std;
const int c = 450;
struct Node {
int id, region, low, high;
vector<int> children;
};
struct Region {
vector<int> ids;
vector<pair<int, int>> ranges;
int depth;
Region() : ids(), ranges(), depth(0) {}
};
Node nodes[200001];
Region regions[25001];
ll ans1[450][25001], ans2[25001][450];
int maps_to[25001];
void dfs(int node, int& id_pool) {
int id = id_pool++;
int r = nodes[node].region;
regions[r].ids.push_back(id);
regions[r].depth++;
regions[r].ranges.push_back({id_pool, regions[r].depth});
for (int i : nodes[node].children) dfs(i, id_pool);
regions[r].depth--;
regions[r].ranges.push_back({id_pool, regions[r].depth});
}
ll query(Region a, Region b) {
if (a.ranges.empty()) return 0;
ll ans = 0;
vector<int>::iterator id = b.ids.begin();
while (id != b.ids.end() && *id < a.ranges[0].first) id++;
for (int i = 0; i < a.ranges.size() - 1 && id != b.ids.end(); i++) {
int pos2 = a.ranges[i + 1].first;
ll depth = a.ranges[i].second;
vector<int>::iterator old = id;
while (id != b.ids.end() && *id < pos2) id++;
ans += depth * (id - old);
}
return ans;
}
int main() {
int n, r, q;
cin >> n >> r >> q >> nodes[1].region;
FOR(i, 2, n + 1) {
int p;
cin >> p >> nodes[i].region;
nodes[p].children.push_back(i);
}
int id_pool = 1;
dfs(1, id_pool);
int cnt = 1;
FOR(i, 1, r + 1) {
if (regions[i].ids.size() > c) {
FOR(j, 1, r + 1) {
ans1[cnt][j] = query(regions[i], regions[j]);
ans2[j][cnt] = query(regions[j], regions[i]);
}
maps_to[i] = cnt++;
}
}
while (q--) {
int a, b;
cin >> a >> b;
if (regions[a].ids.size() > c) cout << ans1[maps_to[a]][b] << endl;
else if (regions[b].ids.size() > c) cout << ans2[a][maps_to[b]] << endl;
else cout << query(regions[a], regions[b]) << endl;
}
return 0;
}
Compilation message (stderr)
regions.cpp: In function 'll query(Region, Region)':
regions.cpp:46:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int i = 0; i < a.ranges.size() - 1 && id != b.ids.end(); i++) {
~~^~~~~~~~~~~~~~~~~~~~~| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |