Comment

avatar username

You need to store the answer for every node after finishing, here what I would modify:

Code
int ans[100100]; // Here

void dfs(int node, int parent) {
    par[node] = parent;

    // Insert the node's value into its own set
    uunique[node].insert(val[node]);

    for (auto neigh : g[node]) {
        if (neigh != parent) {
            dfs(neigh, node);

            // Small-to-large merging: merge smaller set into the larger one
            if (uunique[neigh].size() > uunique[node].size()) {
                swap(uunique[node], uunique[neigh]);
            }
            uunique[node].insert(uunique[neigh].begin(), uunique[neigh].end());
        }
    }

    ans[node] = uunique[node].size(); // Here
}

The actual rating of this user is 1409.

Original comment.

Statistics