1997D - Maximize the Root - CodeForces Solution


binary search dfs and similar dp greedy trees

Please click on ads to support us..

Python Code:

def findval(vals,parents,childs,i,arr):
    l1 = [i]
    l2 = []
    while l1 != []:
        xx = l1.pop()
        l2.append(xx)
        for ii in childs[xx]:
            l1.append(ii)
    while l2 != []:
        xx = l2.pop()
        if childs[xx] == []:
            arr[xx] = vals[xx]
        else:
            minchildval = 1e9
            for j in childs[xx]:
                minchildval = min(minchildval,arr[j])
            if vals[xx] < minchildval:
                arr[xx] = (vals[xx]+minchildval)//2
            else:
                arr[xx] = minchildval
    return arr[i]

def findminvalfr(vals,parents,childs):
    x = 1e9
    arr = [-1 for i in range(len(vals))]
    for i in childs[0]:
        x = min(x,findval(vals,parents,childs,i,arr))
    return x

num = int(input())
out = []
for x in range(num):
    n = int(input())
    vals = [int(i) for i in input().split()]
    parents = [-1] + [int(i)-1 for i in input().split()]
    childs = []
    for i in range(n):
        childs.append([])
    for i in range(1,n):
        childs[parents[i]].append(i)
    if childs[0] == []:
        out.append(vals[0])
        continue
    minfr = findminvalfr(vals,parents,childs)
    out.append(vals[0]+minfr)

for i in out:
    print(int(i))


Comments

Submit
0 Comments
More Questions

1101A - Minimum Integer
985D - Sand Fortress
1279A - New Year Garland
1279B - Verse For Santa
202A - LLPS
978A - Remove Duplicates
1304A - Two Rabbits
225A - Dice Tower
1660D - Maximum Product Strikes Back
1513A - Array and Peaks
1251B - Binary Palindromes
768B - Code For 1
363B - Fence
991B - Getting an A
246A - Buggy Sorting
884A - Book Reading
1180A - Alex and a Rhombus
445A - DZY Loves Chessboard
1372A - Omkar and Completion
159D - Palindrome pairs
981B - Businessmen Problems
1668A - Direction Change
1667B - Optimal Partition
1668B - Social Distance
88B - Keyboard
580B - Kefa and Company
960A - Check the string
1220A - Cards
897A - Scarborough Fair
1433B - Yet Another Bookshelf