Search
 
SCRIPT & CODE EXAMPLE
 

CPP

Distinct Colors cses solution

#include<bits/stdc++.h>
using namespace std;
#define SZ 200005
 
int n, m, k, u, v;
vector<int> adj[SZ];
int ans[SZ];
int col[SZ];
 
set<int> dfs(int u, int p) {
	set<int> uniq;
	uniq.insert(col[u]);
 
	for(int v: adj[u]) {
		if(v!=p) {
			set<int> child = dfs(v, u);
			if(child.size() > uniq.size()) swap(child, uniq);
			for(int color: child) {
				uniq.insert(color);
			}
		}
	}
	ans[u] = uniq.size();
	return uniq;
}
 
 
int main() {
	cin >> n;
 
	for(int i = 1; i <= n; i++) 
		cin >> col[i];
	
	for(int i = 0; i < n-1; i++) {
		cin >> u >> v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}
	dfs(1, 0);
	
	for(int i=1; i<=n; i++)
	cout << ans[i] << " ";
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: c++ program to add two numbers using function 
Cpp :: qstring get if empty 
Cpp :: dlopen failed: library "libomp.so" not found 
Cpp :: pass c++ 
Cpp :: how to writt array in c++ 
Cpp :: Arduino Sring to const char 
Cpp :: number to binary string c++ 
Cpp :: print vector 
Cpp :: c++ find sum of vector 
Cpp :: qstring to char* 
Cpp :: quadratic problem solution c++ 
Cpp :: how to make crypto 
Cpp :: helloworld in c++ 
Cpp :: how to loop a 2 dimensional vector in c++ starting from second element 
Cpp :: what is _asm in C++ 
Cpp :: c++ matrix as argument 
Cpp :: c++ mst kruskal 
Cpp :: qt popup window 
Cpp :: how to do (binary) operator overloading in c++ 
Cpp :: unordered_map header file c++ 
Cpp :: c++ reverse integer 
Cpp :: Frequency of a substring in a string C++ 
Cpp :: how to put bitset into a string in c++ 
Cpp :: sleep system function linux c++ 
Cpp :: file open cpp 
Cpp :: cpp ifstream 
Cpp :: overload stream extract cpp 
Cpp :: how to add an element to std::map 
Cpp :: hamming distance c++ 
Cpp :: sort index c++ 
ADD CONTENT
Topic
Content
Source link
Name
2+9 =