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

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 →


You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →