Coloring Tree


Problem Statement :


You are given a tree with N nodes with every node being colored. A color is represented by an integer ranging from 1 to 109. Can you find the number of distinct colors available in a subtree rooted at the node s?


Input Format

The first line contains three space separated integers representing the number of nodes in the tree (N), number of queries to answer (M) and the root of the tree.

In each of the next N-1 lines, there are two space separated integers(a b) representing an edge from node a to Node b and vice-versa.

N lines follow: N+ith line contains the color of the ith node.

M lines follow: Each line containg a single integer s.

Output Format

Output exactly M lines, each line containing the output of the ith query.


Constraints

0 <= M <= 105
1 <= N <= 105
1 <= root <= N
1 <= color of the Node <= 109



Solution :



title-img


                            Solution in C :

In   C++  :







#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<map>
#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

#define foreach(e, x) for(__typeof(x.begin()) e = x.begin(); e != x.end(); ++ e)
#define next nxt

const int N = 100000 + 10;
const int MOD = 1000000000 + 7;

int n, m, r;
int tot;
vector<int> adj[N];
int color[N];
int father[N];
int sqn[N];
int ret[N];
int ord[N][2];
int next[N];
int c[N];
pair< pair<int, int>, int> query[N];

void dfs(int u)
{
	sqn[tot] = color[u];
	ord[u][0] = tot ++;
	foreach(it, adj[u]) {
		int v = *it;
		if (v == father[u]) continue;
		father[v] = u;
		dfs(v);
	}
	ord[u][1] = tot;
}

void add(int u, int x)
{
	for( ; u <= n; u += u & -u)
		c[u] += x;
}

int ask(int u)
{
	int ret = 0;
	for( ; u; u -= u & -u)
		ret += c[u];
	return ret;
}

void solve()
{
	cin >> n >> m >> r;
	int u, v;
	for(int i = 1; i < n; ++ i) {
		scanf("%d%d", &u, &v);
		-- u, -- v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}
	-- r;
	father[r] = -1;
	for(int i = 0; i < n; ++ i) {
		scanf("%d", &color[i]);
	}
	tot = 0;
	dfs(r);
	for(int i = 0; i < n; ++ i) {
		query[i] = make_pair(make_pair(ord[i][0], ord[i][1]), i);
	}
	sort(query, query + n);
	map<int, int> s;
	for(int i = n - 1; i >= 0; -- i) {
		if (s.count(sqn[i]) == 0) {
			next[i] = -1;
		} else {
			next[i] = s[sqn[i]];
		}
		s[sqn[i]] = i;
	}
	foreach(it, s) {
		add(it->second + 1, 1);
	}
	int l, r;
	int ptr = 0;
	for(int i = 0; i < n; ++ i) {
		l = query[i].first.first;
		r = query[i].first.second;
		for ( ; ptr < l; ) {
			if (next[ptr] != -1)
				add(next[ptr] + 1, 1);
			++ ptr;
		}
		ret[query[i].second] = ask(r) - ask(l);
	}
	for(int i = 0; i < n; ++ i) {
	}
	for(int i = 0; i < m; ++ i) {
		scanf("%d", &u);
		-- u;
		printf("%d\n", ret[u]);
	}
}

int main()
{
	solve();
	return 0;
}








In   Java  :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class ColoringTree {
public static class TreeNode {
ArrayList<TreeNode> ch;
int color, numberOfColors;
boolean visited;

TreeNode() {
ch = new ArrayList<TreeNode>();
visited = false;
}
}

public static TreeSet<Integer> colors(TreeNode node) {
TreeSet<Integer> combined;
node.visited = true;
combined = new TreeSet<Integer>();
LinkedList<TreeSet<Integer>> childColors 
= new LinkedList<TreeSet<Integer>>();
for (TreeNode child : node.ch) {
if (child.visited)
continue;
TreeSet<Integer> col = colors(child);
if (col.size() > combined.size())
combined = col;
childColors.add(col);
}
for (TreeSet<Integer> col : childColors) {
if (col != combined)
combined.addAll(col);
}
combined.add(node.color);
node.numberOfColors = combined.size();
return combined;
}

public static void main(String[] args) {
int n, m, root;
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
root = in.nextInt();
TreeNode[] nodes = new TreeNode[n + 1];
for (int i = 1; i <= n; i++)
nodes[i] = new TreeNode();
for (int i = 0; i < n - 1; i++) {
int a, b;
a = in.nextInt();
b = in.nextInt();
nodes[a].ch.add(nodes[b]);
nodes[b].ch.add(nodes[a]);
}
for (int i = 1; i <= n; i++) {
nodes[i].color = in.nextInt();
}
colors(nodes[root]);
for (int i = 0; i < m; i++) {
System.out.println(nodes[in.nextInt()].numberOfColors);
}

}
}








In   Python3 :







from collections import Counter
n, m, root = map(int, input().split())
uniquenum = dict()
multipleset = dict()
adj = dict()
for _ in range(n-1):
    n1, n2 = map(int, input().split())
    if n1 in adj:
        adj[n1].add(n2)
    else:
        adj[n1] = set([n2])
    if n2 in adj:
        adj[n2].add(n1)
    else:
        adj[n2] = set([n1])

colors = [int(input()) for _ in range(n)]
multiples = set(Counter(colors)-Counter(set(colors)))
colors.insert(0, 0)
totalcolors = len(set(colors[1:]))

stack = [root]
added = set([root])
visited = set()
while len(stack)>0:
    node = stack[len(stack)-1]
    if node not in visited:
        visited.add(node)
        for child in adj[node]-added:
            stack.append(child)
            added.add(child)
    else:
        if colors[node] in multiples:
            uniquenum[node] = 0
            multipleset[node] = set([colors[node]])
        else:
            uniquenum[node] = 1
            multipleset[node] = set()
        for child in adj[node]-added:
            uniquenum[node] += uniquenum[child]
            multipleset[node] |= multipleset[child]
        stack.pop()
        added.remove(node)   

for _ in range(m):
    node = int(input())
    print(uniquenum[node]+len(multipleset[node]))
                        








View More Similar Problems

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →