Company Retreat


Problem Statement :


The LRT Company has  employees. Each employee has a unique ID number from 1  to n , where the director's ID is number 1. Every employee in the company has exactly one immediate supervisor — except the director, who has no supervisor. The company's employee hierarchy forms a tree of employee IDs that's rooted at employee number  (the director).

The director decides to have a retreat lasting  days. Each day, the employees will be assigned to different groups for team building exercises. Groups are constructed in the following way:

An employee can invite their immediate supervisor (the director has no supervisor and, thus, doesn't invite anyone). If employee  is invited by employee , then  and  are considered to be in the same group.
Once an employee is invited to be in a group, they are in that group. This means that if two employees have the same immediate supervisor, only one of them can invite that supervisor to be in their group.
Every employee must be in a group, even if they are the only employee in it.
The venue where LRT is hosting the retreat has different pricing for each of the  days of the retreat. For each day , there is a cost of  dollars per group and a per-group size limit of  (i.e., the maximum number of people that can be in any group on that day).

Help the director find optimal groupings for each day so the cost of the -day retreat is minimal, then print the total cost of the retreat. As this answer can be quite large, your answer must be modulo .


Input Format

The first line contains two space-separated integers denoting the respective values of  (the number of employees) and  (the retreat's duration in days).
The next line contains  space-separated integers where each integer  denotes  (), which is the ID number of employee 's direct supervisor.
Each line  of the  subsequent lines contain two space-separated integers describing the respective values of  (the cost per group in dollars) and  (the maximum number of people per group) for the  day of the retreat.

Constraints

1  <=  n, m  <=  10^5
1  <=   Si  <=  n
1  <=  dj, pj  <=  10^9


Output Format

Print a single integer denoting the minimum total cost for the -day retreat. As this number can be quite large, print your answer modulo 10^9 + 7.


Sample Input

7 3
1 1 3 4 2 4
5 3
6 2
1 1


Sample Output

46



Solution :



title-img


                            Solution in C :

In   C++  :







#include "bits/stdc++.h"

using namespace std;

typedef long long ll;
typedef pair < int, int > ii;

const int N = 1 << 17;
const int LOG = 17;

int n, m, tick, cnt;
int dep[N], st[N], nd[N], a[N], leaf[N];
vector < int > v[N], q[N];

int t[N << 1], sparse[LOG][N];

void up(int x, int k) {
    t[x += N] = k;
    while(x > 1) {
        x >>= 1;
        t[x] = min(t[x + x], t[x + x + 1]);
    }
}

int get(int l, int r) {
    int res = 1e9;
    for(l += N, r += N; l <= r; l = (l + 1) >> 1, r = (r - 1) >> 1) {
        if(l & 1) res = min(res, t[l]);
        if(~r & 1) res = min(res, t[r]);
    }
    return res;
}

void dfs(int p, int x) {
    st[x] = ++tick;
    dep[x] = dep[p] + 1;
    sparse[0][x] = p;
    for(int i = 1; i < LOG; i++)
        sparse[i][x] = sparse[i - 1][sparse[i - 1][x]];
    leaf[x] = 1e9;
    for(auto u : v[x]) {
        dfs(x, u);
        leaf[x] = min(leaf[x], leaf[u] + 1);
    }
    if(leaf[x] > 5e8) {
        leaf[x] = 0;
        cnt++;
    }
    q[leaf[x]].push_back(x);
    nd[x] = tick;
}

int calc(int group) {
    int res = cnt;
    priority_queue < ii > Q;
    for(auto x : q[group])
        Q.push({dep[x], x});
    vector < int > vv;
    while(!Q.empty()) {
        int x = Q.top().second;
        Q.pop();
        if(leaf[x] < group or get(st[x], nd[x]) - dep[x] < group)
            continue;
        vv.push_back(x);
        up(st[x], dep[x]);
        res++;
        if(dep[x] > group) {
            int k = group;
            for(int i = LOG - 1; i >= 0; i--) {
                if(k >= (1 << i)) {
                    k -= 1 << i;
                    x = sparse[i][x];
                }
            }
            Q.push({dep[x], x});
        }
    }
    for(auto x : vv)
        up(st[x], 1e9);
    return res;
}

int main () {

    for(int i = 1; i < N + N; i++)
        t[i] = 1e9;

    scanf("%d %d", &n, &m);

    for(int i = 2; i <= n; i++) {
        int x;
        scanf("%d", &x);
        v[x].push_back(i);
    }

    dfs(0, 1);

    for(int i = 1; i <= n; i++)
        a[i] = calc(i);

    ll ans = 0;

    for(int i = 1; i <= m; i++) {
        int x, y;
        scanf("%d %d", &x, &y);
        ans += (ll) x * a[min(n, y)];
        ans %= (int) 1e9 + 7;
    }

    printf("%lld\n", ans);

    return 0;

}








In   Java :





import java.io.*;
import java.util.*;

public class Solution {

static final int logN = 17;
static final int INF = 1000000000;
static final int MOD = 1_000_000_007;

static int[] nxtV;
static int[] succV;
static int[] ptrV;
static int indexV = 1;

static void addV(int u, int v) {
nxtV[indexV] = ptrV[u];
ptrV[u] = indexV;
succV[indexV++] = v;
}

static int[] nxtG;
static int[] succG;
static int[] ptrG;
static int indexG = 1;

static void addG(int u, int v) {
nxtG[indexG] = ptrG[u];
ptrG[u] = indexG;
succG[indexG++] = v;
}

static int tick = 0;
static int[][] lca;
static int[] start;
static int[] dist;
static int[] depth;
static int[] d;
static int[] finish;

static class NodeDfs {
int u;
int p;
boolean start = true;
boolean flag = true;

public NodeDfs(int u, int p) {
this.u = u;
this.p = p;
}
}

static void dfs() {
Deque<NodeDfs> deque = new LinkedList<>();
deque.add(new NodeDfs(1, 0));
while (!deque.isEmpty()) {
NodeDfs node = deque.peekLast();
if (node.start) {
lca[0][node.u] = node.p;
start[node.u] = ++tick;
dist[node.u] = INF;
depth[node.u] = depth[node.p] + 1;
d[start[node.u]] = depth[node.u];
for (int i = ptrV[node.u]; i > 0; i = nxtV[i]) {
int v = succV[i];
if (v != node.p) {
node.flag = false;
deque.add(new NodeDfs(v, node.u));
}
}

node.start = false;
} else {
if (node.flag) {
dist[node.u] = 0;
}
addG(dist[node.u], node.u);
finish[node.u] = tick;

dist[node.p] = Math.min(dist[node.p], dist[node.u] + 1);

deque.removeLast();
}
}
}

static int up(int node, int k) {
for (int i = logN; i >= 0; i--) {
if ((k & (1 << i)) > 0) {
node = lca[i][node];
}
}
return node;
}

static int[] segTree;

static int update(int k, int bas, int son, int x, int y) {
if (bas > x || son < x) {
return segTree[k];
}
if (bas == son) {
return segTree[k] = (y == 1 ? d[bas] : INF);
}
return segTree[k] =
Math.min(
update(k + k, bas, (bas + son) >> 1, x, y),
update(k + k + 1, ((bas + son) >> 1) + 1, son, x, y));
}

static int query(int k, int bas, int son, int x, int y) {
if (bas > y || son < x) {
return INF;
}
if (x <= bas && son <= y) {
return segTree[k];
}
return Math.min(
query(k + k, bas, (bas + son) >> 1, x, y),
query(k + k + 1, ((bas + son) >> 1) + 1, son, x, y));
}

static class Pair implements Comparable<Pair> {

private int first;
private int second;

public Pair(int first, int second) {
this.first = first;
this.second = second;
}

public int compareTo(Pair other) {
if (first < other.first) return 1;
else if (first > other.first) return -1;
else if (second < other.second) return 1;
else if (second > other.second) return -1;
else return 0;
}
}

public static void main(String[] args)
throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(
new FileWriter(System.getenv("OUTPUT_PATH")));

StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());

nxtV = new int[n + 1];
succV = new int[n + 1];
ptrV = new int[n + 1];

st = new StringTokenizer(br.readLine());
for (int i = 2; i <= n; i++) {
int item = Integer.parseInt(st.nextToken());
addV(item, i);
}

nxtG = new int[n + 1];
succG = new int[n + 1];
ptrG = new int[n + 1];

lca = new int[logN + 1][n + 1];
start = new int[n + 1];
dist = new int[n + 1];
depth = new int[n + 1];
d = new int[n + 1];
finish = new int[n + 1];

dfs();

for (int i = 1; i <= logN; i++) {
for (int j = 1; j <= n; j++) {
lca[i][j] = lca[i - 1][lca[i - 1][j]];
}
}

int cur = 0;
segTree = new int[(n + 1) << 2];

for (int i = 1; i <= n; i++) {
if (dist[i] == 0) {
update(1, 1, n, start[i], 1);
cur++;
} else {
update(1, 1, n, start[i], 0);
}
}

List<Integer> del = new ArrayList<>();
PriorityQueue<Pair> queue = new PriorityQueue<>();
int[] ans = new int[n + 1];

ans[1] = n;

for (int i = 2; i <= n; i++) {
int all = cur;
for (int j = ptrG[i]; j > 0; j = nxtG[j]) {
int v = succG[j];
queue.add(new Pair(depth[v], v));
}
del.clear();
while (!queue.isEmpty()) {
int node = queue.remove().second;
if (query(1, 1, n, start[node], 
finish[node]) - depth[node] < i) {
continue;
}
update(1, 1, n, start[node], 1);
all++;
del.add(node);
int up = up(node, i);
if (up > 0) {
queue.add(new Pair(depth[up], up));
}
}
ans[i] = all;
for (int j = 0; j < del.size(); j++) {
update(1, 1, n, start[del.get(j)], 0);
}
}

long result = 0;
for (int i = 1; i <= m; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
result = (result + (
ans[Math.min(n, y)] * (long) x) % MOD) % MOD;
}

bw.write(String.valueOf(result));
bw.newLine();

bw.close();
br.close();
}
}







In    Python3  :





#!/bin/python3

import os
import sys

# Complete the solve function below.
def solve(supervisors, groups):
    n = len(supervisors)+1 
    mHeight = 1
    emps = [0]*n
    for i in range(n-1):
        emps[supervisors[i]-1]+=1
    leaves = []
    for i in range(n):
        if emps[i]==0:
            leaves.append(i+1)
    ll = len(leaves)
    for l in leaves:
        x = l
        h = 1
        while x != 1:
            x = supervisors[x-2]
            h += 1
        mHeight = max(h,mHeight)      
    price = 0
    groupsPerSize = {}
    spans = {}
    for x in groups:
        c = x[0]
        s = x[1]
        if s >= mHeight:
            price += (c * ll) % (10**9+7)
            continue
        elif s not in groupsPerSize:
            height = [[0,emps[i]] for i in range(n)]
            for l in leaves:
                x = l
                while x != 1 and height[x-1][1]==0:
                    y = supervisors[x-2]
                    height[y-1][0] = max(height[y-1][0],(height[x-1][0]-1) % s)
                    height[y-1][1] -= 1
                    x = y
            groupsPerSize[s] = sum(height[i][0] % s == 0 for i in range(n))
            if groupsPerSize[s] not in spans:
                spans[groupsPerSize[s]]=[s,s]
            elif s < spans[groupsPerSize[s]][0]:
                for i in range(s+1,spans[groupsPerSize[s]][0]):
                    groupsPerSize[i]=groupsPerSize[s]  
                spans[groupsPerSize[s]][0]=s
            elif s > spans[groupsPerSize[s]][1]:
                for i in range(spans[groupsPerSize[s]][0]+1,s):
                    groupsPerSize[i]=groupsPerSize[s]  
                spans[groupsPerSize[s]][1]=s
        price += (c * groupsPerSize[s]) % (10**9+7)
    return price % (10**9+7)
        
    

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nm = input().split()

    n = int(nm[0])

    m = int(nm[1])

    supervisors = list(map(int, input().rstrip().split()))

    groups = []

    for _ in range(m):
        groups.append(list(map(int, input().rstrip().split())))

    result = solve(supervisors, groups)

    fptr.write(str(result) + '\n')

    fptr.close()
                        








View More Similar Problems

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

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: where: { 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 a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →