CSES - Shared codeLink to this code:
https://cses.fi/paste/e5bcaa36945e6b663c8bb1/
// हर हर महादेव
#include <bits/stdc++.h>
using namespace std;
vector<int> Enter,Exit,order;
void traverse(vector<vector<int>> &adj,int root = 0){
int V = adj.size();
order.clear();
Enter.clear();Enter.resize(V);
Exit.clear();Exit.resize(V);
int travel_time = 0;
function<void(int,int)> traverse_tree = [&](int i, int parent){
order.push_back(i);
Enter[i] = travel_time++;
for(int node : adj[i]){
if(node != parent){
traverse_tree(node,i);
}
}
order.push_back(i);
Exit[i] = travel_time++;
};traverse_tree(root,-1);
}
bool anc(int child, int ancestor){ // If ansector is an ancestor of child
return Enter[ancestor] < Enter[child] && Exit[child] < Exit[ancestor];
}
template <typename T>
class fenwick {
public:
vector<T> fenw;
int n;
fenwick(int _n) : n(_n) {
fenw.resize(n);
}
void add(int x, T v) {
assert(x < n && x >= 0);
while (x < n) {
combine(fenw[x],v);
x |= (x + 1);
}
}
T find(int x) {
assert(x < n && x >= 0);
T v{};
while (x >= 0) {
combine(v,fenw[x]);
x = (x & (x + 1)) - 1;
}
return v;
}
T find(int l,int r) {
return find(r) - (l == 0 ? 0 : find(l-1));
}
void combine(T &v, T val){
v += val;
}
};
int main(){
ios::sync_with_stdio(false);cin.tie(0);
int n;
cin >> n;
vector<vector<int>> graph(n);
vector<int> color(n);
for(int i = 0; i < n; i++){
cin >> color[i];
}
for(int i = 0; i < n-1; i++){
int u,v;
cin >> u >> v;
u--;v--;
graph[u].push_back(v);
graph[v].push_back(u);
}
traverse(graph);
vector<vector<pair<int,int>>> qu(2*n);
for(int i = 0; i < n; i++){
qu[Exit[i]].push_back({Enter[i],i});
}
fenwick<int> tr(2*n);
map<int,int> last;
vector<int> ans(n);
for(int i = 0; i < 2*n; i++){
int x = color[order[i]];
if(last.find(x) != last.end()){
tr.add(last[x],-1);
}
tr.add(i,1);
last[x] = i;
for(auto [l,j] : qu[i]){
ans[j] = tr.find(l,i);
}
}
for(int i = 0; i < n; i++){
cout << ans[i] << ' ';
}
return 0;
}