Kitty's Calculations on a Tree

Problem Statement :

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from  1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set:


{ u ,v } denotes an unordered pair of nodes belonging to the set.
 dist(u , v) denotes the number of edges on the unique (shortest) path between nodes  and .
Given T and q sets of k  distinct nodes, calculate the expression for each set. For each set of nodes, print the value of the expression modulo 10^9 + 7  on a new line.

Input Format

The first line contains two space-separated integers, the respective values of n (the number of nodes in tree T ) and  q (the number of nodes in the query set).
Each of the n - 1  subsequent lines contains two space-separated integers, a and b, that describe an undirected edge between nodes  and .
The 2 * q subsequent lines define each set over two lines in the following format:

The first line contains an integer, k  , the size of the set.
The second line contains  k space-separated integers, the set's elements.

Output Format

Print q lines of output where each line i contains the expression for the ith query, modulo 10^9 + 7.

Solution :


                            Solution in C :

In C ++ :

#include <bits/stdc++.h>

using namespace std;

const int MOD=1000000007;
int N, Q;
vector<int> adj[200001];
vector<int> adj2[200001];
int P[18][200001];
int depth[200001];
int in[200001];
int out[200001];
int now;
int A[400001];
int mul[200001];
long long sum[200001];

void dfs(int u, int p)
    for(int i=1; i<18; i++)
    for(auto& v: adj[u]) if(v!=p)
        dfs(v, u);

int lca(int u, int v)
        swap(u, v);
    for(int i=17; i>=0; i--) if(depth[P[i][u]]>=depth[v])
        return u;
    for(int i=17; i>=0; i--) if(P[i][u]!=P[i][v])
        u=P[i][u], v=P[i][v];
    return P[0][u];

int dfs2(int u, long long tot)
    int ret=0;
    for(auto& v: adj2[u])
        ret=(ret+dfs2(v, tot))%MOD;
    for(auto& v: adj2[u])
    return ret;

int main()
    scanf("%d%d", &N, &Q);
    for(int i=0; i<N-1; i++)
        int a, b;
        scanf("%d%d", &a, &b);
    dfs(1, 1);
        int K;
        scanf("%d", &K);
        long long tot=0;
        for(int i=0; i<K; i++)
            scanf("%d", A+i), mul[A[i]]=1, tot+=A[i];
        sort(A, A+K, [](int a, int b) {
            return in[a]<in[b];
        for(int i=0; i<K-1; i++)
            A[i+K]=lca(A[i], A[i+1]);
        sort(A, A+2*K-1);
        int M=unique(A, A+2*K-1)-A;
        sort(A, A+M, [](int a, int b) {
            return out[a]-in[a]>out[b]-in[b];
        int root=A[0];
        map<int, int> m;
        for(int i=1; i<M; i++)
            int u=A[i];
            auto it=m.upper_bound(in[u]);
            int p=it->second;
            //printf("%d -> %d\n", p, u);
            if(out[u]<out[p] && (!m.count(out[u]+1) || P[0][m[out[u]+1]]!=p))
        printf("%d\n", dfs2(root, tot));
        for(int i=0; i<M; i++)
            adj2[A[i]].clear(), mul[A[i]]=0;
    return 0;

In Java :

import java.util.Arrays;
import java.util.Scanner;

public class KittysCalc {
	public static final long constant = 1000000007;
	public static void main(String[] args) {
	Scanner sc = new Scanner(;
	int n = sc.nextInt();
	int queries = sc.nextInt();
	int[] parents = new int[n+1];
	long[] children = new long[n+1];
	boolean[] valuesSet = new boolean[n+1];
	long valuesSum = 0;
	long sum = 0;
	int a, b;
	for(int i = 0; i < n-1; i++) {
		a = sc.nextInt();
		b = sc.nextInt();
		if(a < b) {
			parents[b] = a;
		} else {
			parents[a] = b;
	parents[1] = 0;
	for(int i = 0; i < queries; i++) {
		int k = sc.nextInt();
		Arrays.fill(valuesSet, false);
		Arrays.fill(children, 0);
		valuesSum = 0;
		for(int j = 0; j < k; j++) {
			a = sc.nextInt();
			valuesSum += a;
			valuesSet[a] = true;
		sum = 0;
		for (int j = n; j > 0; j--) {
		long c = children[j];
		if (valuesSet[j]) {
			c += j;
		if (c > 0) {
		long x = ((c % constant) * ((valuesSum - c) % constant)) % constant;
		if (constant - sum < x) {
			sum -= constant;
		sum += x;
	children[parents[j]] += c;


In Python3 :

#!/usr/bin/env python3

def put(d, a, b):
    if a in d: d[a].append(b)
    else: d[a] = [b]

def main():
    for n in ns[::-1]:
        r = [tt[s] for s in tree[n] if s != f[n]]
        bst = {s: [gl[n], n, 0] for s in queries[n]}
        if r:
            o = max(range(len(r)), key=lambda a: len(r[a]))
            if len(r[o]) > len(bst): r[o], bst = bst, r[o]
        ry = {}
        for ae in r:
            for y, v in ae.items():
                put(ry, y, v)
        for y, r in ry.items():
            eq, z, t = 0, 0, 0
            if len(r) == 1 and y not in bst:
                bst[y] = r[0]
            if y in bst: r.append(bst.pop(y))
            for d, v, c in r:
                eq += (d - gl[n]) * v + c
                z += v
            for d, v, c in r:
                c += (d - gl[n]) * v
                diff = (eq - c) * v
                t += diff
            returns[y] += t
            bst[y] = (gl[n], z, eq)
        tt[n] = bst
def locate():
    q = [r]
    level = 0
    while q:
        level += 1
        tmp = []
        for n in q:
            for s in tree[n]:
                if s not in f:
                    f[s] = n
                    gl[s] = level
        q = tmp
tree = {}
tt = {}
n, q = map(int, input().split())
returns = [0] * q
for _ in range(n - 1):
    a, b = map(int, input().split())
    put(tree, a, b)
    put(tree, b, a)
queries = {a: set() for a in tree}
for y in range(q):
    for x in map(int, input().split()): queries[x].add(y)
r = next(iter(tree))
ns = []
f = {r: None}
gl = {r: 0}
for s in returns: print(s % (10**9 + 7))

View More Similar Problems

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

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 →