Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // <3 Appy!
- #include "bits/stdc++.h"
- using namespace std;
- typedef unsigned long long ull;
- typedef long long int ll;
- typedef vector<long long int> vi;
- typedef pair<int,int> pii;
- int n,t;
- int a[222222], l[222222], r[222222], visit[222222], x[(ll)1e6];
- ll res[222222], puf[222222], refe[222222], bound[222222], sum;
- vector<pair<pii,int> > w;
- vi v[(ll)1e5+9];
- ll chu = 0;
- int kj[222222];
- ll dfs(int x)
- {
- visit[x] = 1;
- chu++;
- ll k = chu;
- res[k] = x;
- refe[x] = k;
- if(v[x].size() == 0)
- {
- bound[k] = k;
- return (k);
- }
- ll ans = k;
- for(int i=0;i<v[x].size();i++)
- {
- if(visit[v[x][i]] == 0)
- {
- visit[v[x][i]] = 1;
- ans = max(dfs(v[x][i]), ans);
- }
- }
- bound[k] = ans;
- return ans;
- }
- int main()
- {
- ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
- cin>>n>>t;
- ll root;
- for(int i=1;i<=n;i++)
- {
- cin>>a[i];
- if(a[i] == 1)
- root = i;
- }
- for(int i=0;i<n-1;i++)
- {
- ll x,y;
- cin>>x>>y;
- v[x].push_back(y);
- v[y].push_back(x);
- }
- dfs(root);
- ll sq = (ll)sqrtl(n);
- for(int i=0;i<t;i++)
- {
- cin>>l[i]>>kj[i];
- w.push_back(make_pair(pii(refe[l[i]]/sq,bound[l[i]]),i));
- }
- sort(w.begin(),w.end());
- int start = 1;
- int end = 0;
- int ans = 0;
- for(int i=0;i<t;)
- {
- int j=i;
- while(j<t && w[j].first.first==w[i].first.first) j++;
- for(int k = i; k < j; k++)
- {
- int L = l[w[k].second];
- int R = bound[L];
- int p = kj[w[k].second];
- while(start>L)
- {
- start --;
- x[a[res[start]]]++;
- if(x[a[res[start]]] == p) ans++;
- }
- while(start<L)
- {
- if(x[a[res[start]]] == p) ans--;
- x[a[res[start]]]--;
- start ++;
- }
- while(end<R)
- {
- end ++;
- x[a[end]]++;
- if(x[a[res[end]]] == p) ans++;
- }
- while(end>R)
- {
- if(x[a[res[end]]] == p) ans--;
- x[a[res[end]]]--;
- end --;
- }
- puf[w[k].second] = ans;
- }
- i=j;
- }
- for(int i=0;i<t;i++)
- cout<<puf[i]<<" \n";
- return 0;
- }
Add Comment
Please, Sign In to add comment