We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
# https://www.hackerrank.com/contests/w4/challenges/roy-and-alpha-beta-treesimportsysMOD=10**9+9MAX_N=150dp=[[None]*MAX_Nfor_inrange(MAX_N)]defread_numbers():return[int(d)fordinsys.stdin.readline().split()]defsubtree(numbers,start,end):"""Calculates result for all trees from start to end, inclusive."""ifstart==end:return1,0,0ifdp[start][end]isnotNone:returndp[start][end]tree_count=0even_sum=0odd_sum=0foriinrange(start,end):left_count,left_even_sum,left_odd_sum=subtree(numbers,start,i)right_count,right_even_sum,right_odd_sum=subtree(numbers,i+1,end)tree_count=(tree_count+left_count*right_count)%MODeven_sum=(even_sum+numbers[i]*left_count*right_count+left_odd_sum*right_count+right_odd_sum*left_count)%MODodd_sum=(odd_sum+left_even_sum*right_count+right_even_sum*left_count)%MODdp[start][end]=(tree_count,even_sum,odd_sum)returntree_count,even_sum,odd_sumdefsolve(numbers,alpha,beta):globaldpdp=[[None]*MAX_Nfor_inrange(MAX_N)]numbers.sort()tree_count,even_sum,odd_sum=subtree(numbers,0,len(numbers))return(alpha*even_sum-beta*odd_sum)%MODif__name__=='__main__':T=int(sys.stdin.readline())fortinrange(T):n=int(sys.stdin.readline())alpha,beta=read_numbers()numbers=read_numbers()print(solve(numbers,alpha,beta))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Roy and alpha-beta trees
You are viewing a single comment's thread. Return to all comments →
Python3 solution