Find the number of unique values in the subtree of a node .
#include <bits/stdc++.h>
using namespace std;
int par[100100];
int val[100100];
vector<int> g[100100];
set<int> uunique[100100];
void dfs(int node, int parent) {
par[node] = parent;
for (auto neigh : g[node]) {
if (neigh != parent) {
dfs(neigh, node);
}
}
for(auto v : uunique[node]){
uunique[par[node]].insert(v);
}
}
int main() {
int n;
cin >> n;
int m = n - 1;
while (m--) {
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
for (int i = 1; i <= n; i++) {
cin >> val[i];
uunique[i].insert(val[i]);
}
dfs(1, 0);
for (int node = 1; node <= n; node++) {
cout << "Number of unique values in the subtree of " << node
<< " are " << (int)uunique[node].size() << '\n';
}
return 0;
}
This code seems to be for problem CSES — Distinct Colors.
If you did small to large, the complexity would be $$$O(n \cdot \log{(n)}^2)$$$, but this code is $$$O(n^2)$$$
It's $$$O(n^2 \cdot log(n))$$$ actually. It'll be $$$O(n^2)$$$ if use
std::unordered_set
instead ofstd::set
Thanks for the correction
can you please provide me the template code for this
You need to store the answer for every node after finishing, here what I would modify: