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 <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#define INF 1e9
using namespace std;
typedef long long ll;
int timer = 0, ans = 0;
vector<int>adj[100005], g[100005];
int tin[100005], tout[100005], d[100005], p[100005][20], c[100005];
map<pair<int,int>, int>seen;
void dfs(int s, int e) {
	for (int i = 1; i <= 18; i++) {
		p[s][i] = p[p[s][i - 1]][i - 1];
	}
	++timer;
	tin[s] = timer;
	for (auto u : adj[s]) {
		if (u == e) continue;
		d[u] = d[s] + 1;
		p[u][0] = s;
		dfs(u, s);
	}
	tout[s] = timer;
}
int lca(int a, int b) {
	if (d[a] > d[b]) swap(a, b);
	int dis = d[b] - d[a];
	for (int i = 0; i <= 18; i++) {
		if (dis & (1 << i)) b = p[b][i];
	}
	if (a == b) return a;
	for (int i = 18; i >= 0; i--) {
		if (p[a][i] != p[b][i]) {
			a = p[a][i];
			b = p[b][i];
		}
	}
	return p[a][0];
}
bool ancestor(int x, int y) {
	return tin[x] <= tin[y] && tout[y] <= tout[x];
}
bool comp(int x, int y) {
	return tin[x] < tin[y];
}
void dfs1(int s) {
	for (auto u : g[s]) {
		ans += d[u] - d[s];
		dfs1(u);
	}
}
void build(vector<int>& a) {
	sort(a.begin(), a.end(), comp);
	int sz = a.size();
	for (int i = 0; i < sz - 1; i++) {
		a.push_back(lca(a[i], a[i + 1]));
	}
	sort(a.begin(), a.end(), comp);
	a.resize(unique(a.begin(), a.end()) - a.begin());
	stack<int>stk;
	for (auto u : a) {
		while (stk.size() && !ancestor(stk.top(), u))stk.pop();
		if (stk.size()) g[stk.top()].push_back(u);
		stk.push(u);
	}
	//for (int i = 0; i < a.size(); i++) cout << a[i] << " ";
	dfs1(a[0]);
	for (auto u : a) g[u].clear();
}
void solve()
{
	int n, m, q; cin >> n >> m >> q;
	for (int i = 1; i <= n - 1; i++) {
		int u, v; cin >> u >> v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}
	dfs(1, 0);
	for (int i = 1; i <= m; i++) cin >> c[i];
	while (q--) {
		int l, r; cin >> l >> r;
		if (seen[{l, r}] != 0)cout << seen[{l, r}] << "\n";
		else if (l == r) { cout << 1 << "\n"; }
		else {
			vector<int>a;
			ans = 0;
			for (int i = l; i <= r; i++) a.push_back(c[i]);
			build(a);
			cout << ans + 1 << "\n";
			seen[{l, r}] = ans + 1;
		}
	}
}
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	int t = 1;// cin>>t;
	while (t--) solve();
	return 0;
}
| # | 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... |