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>
//#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")
using namespace std;
#define int long long
#define vi vector<int>
#define vl vector<long long>
#define vii vector<pair<int,int>>
#define vll vector<pair<long long,long long>>
#define pb push_back
#define ll long long
#define ld long double
#define nl '\n'
#define boost ios::sync_with_stdio(false)
#define mp make_pair
#define se second
#define fi first
#define fore(i, y) for(int i = 0; i < y; i++)
#define forr(i,x,y) for(int i = x;i<=y;i++)
#define forn(i,y,x) for(int i = y; i >= x; i--)
#define all(v) v.begin(),v.end()
#define sz(v) (int)v.size()
#define clr(v,k) memset(v,k,sizeof(v))
#define rall(v) v.rbegin() , v.rend()
#define pii pair<int,int>
#define pll pair<ll , ll>
const ll MOD = 1e9 + 7;
const ll INF = 1e18 + 1;
ll gcd(ll a , ll b) {return b ? gcd(b , a % b) : a ;} // greatest common divisor (gcd)
ll lcm(ll a , ll b) {return a * (b / gcd(a , b));} // least common multiple (lcm)
// HERE IS THE SOLUTION
int n , m , q;
vector<vi> adj;
vi c;
vi depth;
vi par;
void dfs(int x , int p)
{
for(auto u : adj[x])
{
if(u == p)
continue;
depth[u] = depth[x] + 1;
par[u] = x;
dfs(u , x);
}
}
void get_together(int u , int v , set<int> &vis)
{
if(u == v)
{
vis.insert(u);
return ;
}
if(depth[u] < depth[v])
swap(u , v);
int x = depth[u] - depth[v];
int ans = 0;
vis.insert(u);
while (x--)
{
ans++;
u = par[u];
vis.insert(u);
}
if(u == v)
{
return;
}
vis.insert(v);
while(u != v)
{
ans+=2;
u = par[u];
vis.insert(u);
v = par[v];
vis.insert(v);
}
return ;
}
signed main()
{
boost;
cin.tie(0);
cout.tie(0);
cin>>n>>m>>q;
c = vi (m);
adj.assign(n , {});
depth.assign(n , 0);
par.assign(n , 0);
vector<vi> dp(m , vi(m , INF));
fore(i , n - 1)
{
int u , v;
cin>>u>>v;
u-- , v--;
adj[u].pb(v);
adj[v].pb(u);
}
fore(i , m)
{
cin>>c[i];
c[i]--;
dp[i][i] = 1;
}
dfs(0 , -1);
fore(i , m)
{
set<int> vis;
vis.insert(c[i]);
forr(j , i + 1 , m - 1)
{
get_together(c[j - 1] , c[j] , vis);
dp[i][j] = sz(vis);
}
}
while(q--)
{
int l , r;
cin>>l>>r;
l-- , r--;
set<int> vis;
int i = l;
vis.insert(c[i]);
forr(j , i + 1 , r)
{
get_together(c[j - 1] , c[j] , vis);
}
cout<<sz(vis)<<nl;
}
}
# | 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... |