K - Keen Tree Design

Languages: C, C++, Java, Python, Kotlin
Time & Memory limits: (details)

Input

Output

Sample test(s)

Input
3 1 1 1 2 1 0 1 0
Output
13
Input
4 3 1 2 3 3 0 3 3 0 2 1 0
Output
174
Input
4 1 3 2 3 3 0 3 3 0 2 1 0
Output
72
Input
7 6136 5857 6214 4018 8058 3080 6287 3851 3304 5348 6824 6404 9716 8896 2500 989 8076 1781 7817 5476 9121 5170 9887 3427 5176 3254 9828 6479 1984 5251
Output
5126122548

Hints