Unique Colors


Problem Statement :


You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci.

Let d( i , j )  be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows:


Your task is to print the value of sumi  for each node  1  <=  i  <= n.


Input Format

The first line contains a single integer, n, denoting the number of nodes.
The second line contains n space-separated integers, c1, c2 , c3 , . . . cn , where each ci  describes the color of node i.
Each of the n - 1 subsequent lines contains 2 space-separated integers, a and b, defining an undirected edge between nodes a and b.

Constraints

1  <=   n  <=  10^5
1  <=  ci  <=  10^5

Output Format

Print n lines, where the ith line contains a single integer denoting sumi.


Solution :



title-img


                            Solution in C :

In   C++  :








#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
#define N 101000
typedef long long ll;
set<pi> S;
set<pi> ::iterator it;
int dis[N], rev[N], col[N], pa[N], fin[N];
ll Add[N * 4];
ll ans[N];
vector<int> v[N];
vector<int> C[N];
int cnt;
void dfs(int x, int p) {
    dis[x] = ++cnt;
    rev[cnt] = x;
    C[col[x]].push_back(x);
    for(int i = 0; i < v[x].size(); i ++) {
        int y = v[x][i];
        if(y == p) continue;
        pa[y] = x;
        dfs(y, x);
    }
    fin[x] = cnt;
}
pi A[N];

void build(int st, int en, int id) {
    Add[id] = 0;
    if(st == en) {
        return ;
    }
    int mid = (st + en) >> 1;
    build(st, mid, id * 2);
    build(mid + 1, en, id * 2 + 1);
    return ;
}

int n;

void push_down(int id) {
    if(Add[id]) {
        Add[id * 2] += Add[id];
        Add[id * 2 + 1] += Add[id];
        Add[id] = 0;
    }
    return ;
}

void add(int l, int r, int st, int en, int id, int val) {
    if(l > en || st > r) return ;
    if(l <= st && en <= r) {
        Add[id] += val;
        return ;
    }
    push_down(id);
    int mid = (st + en) >> 1;
    add(l, r, st, mid, id * 2, val);
    add(l, r, mid + 1, en, id * 2 + 1, val);
}

ll calc(int l, int st, int en, int id) {
    if(st == en) {
        return Add[id];
    }
    push_down(id);
    int mid = (st + en) >> 1;
    if(l <= mid) return calc(l, st, mid, id * 2);
    return calc(l, mid + 1, en, id * 2 + 1);
}
pi B[N];

void doit(int y) {
    int st = dis[y];
    int en = fin[y];
    it = S.lower_bound(pi(en + 1, 0));
    if(it == S.begin()) {
        add(st, en, 1, n, 1, -(en - st + 1));
        S.insert(pi(st, en));
        return ;
    }
    it --;
    pi bb = *it;
    if(bb.second < st) {
        add(st, en, 1, n, 1, -(en - st + 1));
        S.insert(pi(st, en));
        return ;
    }
    int cnt = 0;
    while(1) {
        pi aa = *it;
        if(aa.second < st) break;
        B[cnt ++] = aa;
        if(it == S.begin()) break;
        it --;
    }
    for(int i = 0; i < cnt; i ++) A[i] = B[cnt - 1- i];
    int num = en - st + 1;
    for(int i = 0; i < cnt; i ++) num -= (A[i].second - A[i].first + 1);
    for(int i = 1; i < cnt; i ++) {
        if(A[i].first > A[i - 1].second + 1) {
            add(A[i - 1].second + 1, A[i].first - 1, 1, n, 1, -num);
        }
        continue;
    }
    if(A[0].first >= st + 1) add(st, A[0].first - 1, 1, n, 1, -num);
    if(A[cnt - 1].second <= en - 1) add(A[cnt - 1].second + 1, en, 1, n, 1, -num);
    for(int i = 0; i < cnt; i ++) {
        it = S.find(pi(A[i].first, A[i].second));
        S.erase(it);
    }
    S.insert(pi(st, en));
}
int a[N];
int main() {
    //freopen("1.in", "r", stdin);
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++) scanf("%d", &col[i]);
    for(int i = 1; i <= n; i ++) a[i - 1] = col[i];
    sort(a, a + n);
    int num = unique(a, a + n) - a;
    for(int i = 1; i <= n; i ++) col[i] = lower_bound(a, a + num, col[i]) - a + 1;
    for(int i = 1; i <= n; i ++) ans[i] = 1ll * num * n;
    for(int i = 1; i < n; i ++) {
        int x, y;
        scanf("%d%d", &x, &y);
        v[x].push_back(y);
        v[y].push_back(x);
    }
    if(n == 1) {
        puts("0");
        return 0;
    }
    dfs(1, 0);
    build(1, n, 1);
    for(int i = 1; i <= num; i ++) {
        S.clear();
        for(int j = C[i].size() - 1; j >= 0; j --) {
            int x = C[i][j];
            for(int k = 0; k < v[x].size(); k ++) {
                int y = v[x][k];
                if(y == pa[x]) continue;
                doit(y);
            }
            for(int k = 0; k < v[x].size(); k ++) {
                int y = v[x][k];
                if(y == pa[x]) continue;
                S.erase(pi(dis[y], fin[y]));
            }
            S.insert(pi(dis[x], fin[x]));
        }
        doit(1);
    }
    for(int i = 1; i <= n; i ++) ans[i] += calc(i, 1, n, 1);
    for(int i = 1; i <= n; i ++) printf("%lld\n", ans[dis[i]]);
    return 0;
}









In   Java  :







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

public class Solution {
    static BufferedReader br = new
     BufferedReader(new InputStreamReader(System.in));
    static Node[] nodes;
    static int n;
    public static void main(String[] args) throws IOException {
        n = Integer.valueOf(br.readLine());
        nodes = new Node[n];
        String[] line = br.readLine().split(" ");
        for (int i = 0; i < n; i++)
            nodes[i] = new Node(i, Integer.valueOf(line[i]));
        for (int i = 1; i < n; i++) {
            line = br.readLine().split(" ");
            int u = Integer.valueOf(line[0])-1;
            int v = Integer.valueOf(line[1])-1;
            nodes[u].adj.add(nodes[v]);
            nodes[v].adj.add(nodes[u]);
        }
        for (int i = 0; i < n; i++) {
System.out.println(f(i, i, -1, new BitSet(n), new BitSet(n), 0));
        }
    }
    static long f(int start, int index,
     int prev, BitSet visited, BitSet colors, int bitCount) {
        if (visited.get(index))
            return bitCount;
        int color = nodes[index].color;
        boolean increased = false;
        if (!colors.get(color)) {
            colors.set(color);
            bitCount++;
            increased = true;
        }
        
        long sum = bitCount;
        for (Node node : nodes[index].adj) {
            if (node.id != prev)
 sum += f(start, node.id, index, visited, colors, bitCount);
        }
            
        if (increased) {
            colors.clear(color);
            bitCount--;
        }
        visited.clear(index);
        return sum;
    }
}
class Node {
    int id, color;
    List<Node> adj = new ArrayList<Node>();
    public Node(int id, int color) {
        this.id = id; this.color = color;
    }
}









In    Python 3  :







import collections

n = int(input())
node_colors = input().split()
edges = {i: [] for i in range(n)}
for _ in range(n - 1):
    one, two = [int(i) - 1 for i in input().split()]
    edges[one].append(two)
    edges[two].append(one)

def bfs_sum(i):
    value = 0
    seen = {i}
    q = collections.deque([(i, {node_colors[i]})])
    while q:
        t, colors = q.popleft()

        value += len(colors)

        for edge in edges[t]:
            if edge not in seen:
                seen.add(edge)
                q.append((edge, colors | {node_colors[edge]}))
    return value


for i in range(n):
    print(bfs_sum(i))
                        




View More Similar Problems

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →