This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#ifdef Home
#define _GLIBCXX_DEBUG
#endif // Home
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const int N = 100100;
const int LOGN = 17;
vector < int > adj[N];
int up[N][LOGN], depth[N], use[N], T, ans, C[N], n, m, q;
int SpTmin[LOGN][N], SpTmax[LOGN][N];
int lg2(int a) {
return 31 - __builtin_clz(a);
}
int get(int l, int r) {
int m = lg2(r - l + 1);
return max(SpTmax[m][l], SpTmax[m][r - (1<<m) + 1]) -
min(SpTmin[m][l], SpTmin[m][r - (1<<m) + 1]) + 1;
}
void dfs(int v, int p) {
depth[v] = depth[p] + 1;
up[v][0] = p;
for(int i = 1; i < LOGN; ++ i) {
up[v][i] = up[ up[v][i - 1] ][i - 1];
}
for(auto &u : adj[v]) {
if(u != p) {
dfs(u, v);
}
}
}
int slow_LCA(int a, int b) {
if(depth[a] < depth[b]) {
swap(a, b);
}
ans += use[a] != T;
ans += use[b] != T;
use[a] = T;
use[b] = T;
for(; depth[a] > depth[b];) {
a = up[a][0];
if(use[a] == T) {
return b;
}
++ ans;
use[a] = T;
}
for(; a != b;) {
a = up[a][0];
b = up[b][0];
if(a == b) {
use[b] = T;
++ ans;
return a;
}
ans += 2;
use[a] = T;
use[b] = T;
}
return b;
}
void solve_subtask_3() {
for(int i = 1; i <= n; ++ i) {
SpTmax[0][i] = SpTmin[0][i] = C[i];
}
for(int lg = 1; (1<<lg) <= n; ++ lg) {
for(int i = 1; i <= n - (1<<lg) + 1; ++ i) {
SpTmax[lg][i] = max(SpTmax[lg - 1][i], SpTmax[lg - 1][i + (1<<(lg - 1))]);
SpTmin[lg][i] = min(SpTmin[lg - 1][i], SpTmin[lg - 1][i + (1<<(lg - 1))]);
}
}
for(int l, r; q --> 0;) {
cin >> l >> r;
cout << get(l, r) << '\n';
}
}
main() {
#ifdef Home
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif // Home
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m >> q;
bool subtsk3 = true;
for(int i = 1, a, b; i < n; ++ i) {
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
subtsk3 &= (a == i && b == i + 1);
}
for(int i = 1; i <= m; ++ i) {
cin >> C[i];
}
if(subtsk3) {
solve_subtask_3();
return 0;
}
dfs(1, 1);
for(int l, r, m; q --> 0;) {
cin >> l >> r;
ans = 1;
m = C[l ++];
use[m] = ++ T;
for(; l <= r; ++ l) {
m = slow_LCA(m, C[l]);
}
cout << ans << '\n';
}
}
Compilation message (stderr)
tourism.cpp:89:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
89 | main() {
| ^~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |