anirbang749's blog

By anirbang749, history, 31 hour(s) ago, In English

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;
}

Full text and comments »

  • Vote: I like it
  • +5
  • Vote: I do not like it