On a tree whose nodes are black or white with weighted happiness, find the maximum total weight of a path that contains equally many black and white nodes.
Medium6TreePrefix sumDynamic programmingNo attempts yetTime limit1sMemory limit1024 MBYou have just graduated from high school and are looking for a university to enroll in. Bytelandia has N magic universities, and each one teaches either black magic or white magic. There are N−1 bidirectional roads between the universities, and each road connects two different universities. The roads are laid out so that exactly one path exists between any two universities.
You plan to visit some of the universities. Each university has a happiness factor, and visiting it increases your overall happiness by that amount. If the happiness factor is negative, your overall happiness decreases instead.
To plan the trip you pick two different universities, the departure and the destination. You visit every university on the path between them, including both endpoints. To keep the trip balanced, you must visit the same number of white magic universities as black magic universities.
Find the largest possible sum of happiness factors over all trips that visit the same number of black magic and white magic universities.
The input consists of four lines.
The first line contains the number of universities N (2≤N≤105). The universities are numbered from 1 to N.
The second line contains a string of length N made only of the characters "B" and "W". If the i-th character is "B", university i teaches black magic, and if it is "W", university i teaches white magic. At least one university teaches black magic and at least one teaches white magic.
The third line contains the happiness factors h1,h2,…,hN separated by spaces (−105≤hi≤105).
The fourth line contains N−1 integers v1,v2,…,vN−1 separated by spaces. vi means a road connects university vi and university i+1 (1≤vi≤i).
Print one integer, the maximum sum of happiness factors over all trips that visit the same number of black magic and white magic universities.