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

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

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 →