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

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →