# 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 :

```                            ```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() {
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;
}
}

node.start = false;
} else {
if (node.flag) {
dist[node.u] = 0;
}
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 {
BufferedWriter bw = new BufferedWriter(
new FileWriter(System.getenv("OUTPUT_PATH")));

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];

for (int i = 2; i <= n; i++) {
int item = Integer.parseInt(st.nextToken());
}

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];
}
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++;
int up = up(node, i);
if (up > 0) {
}
}
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++) {
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()```
```

## 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

## Waiter

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

## 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

## 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):

## 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.

## Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr