Network Charges
Time limit1sMemory limit256 MB
Choose plan A or B for each leaf of a perfect binary tree to minimize plan-change costs plus pairwise charges set by subtree majorities.
- Level
Hard8 of 10
- Topics
- Graph, Tree, Dynamic programming
- Solved
- No attempts yet
Statement
Networking has become an essential part of the modern world. Each day, hundreds of millions of users use the web for education, research, entertainment, and more. The huge operating costs of networks cannot be ignored, so charging users appropriately is both necessary and reasonable.
City MY's NS high school has an educational network of this kind. The network has users, labeled . The network consists of routers and cables between the users. The users, routers, and cables form a perfect binary tree. Every leaf node is a user, every non-leaf node is a router, and every edge is a network cable.
The company uses a scheme called pairwise charging. A fee is charged for every pair of users and (). Each user independently chooses plan A or plan B, so the charge depends on those choices. The total charge is the sum of all pairwise charges between different users.
Definitions:
- Ancestor: The root node has no ancestors. The ancestors of a non-root node are its parent and the ancestors of its parent.
- Containment of leaf nodes: A leaf node contains no leaf nodes. A non-leaf node contains the leaf nodes of its left child plus the leaf nodes of its right child.
- Distance: The distance between two nodes is the number of edges on the shortest path connecting them.
For two users and (), find the common ancestor router with the smallest distance to each user. Then count, among the leaf nodes (users) contained by , how many chose plan A and how many chose plan B. Call these counts and . The charge is then determined by the table below, where is the known data flow between and .
Users want to change their plans to minimize the total charge to the school. The company has recorded each user's plan at registration. If user changes plan (from A to B or from B to A), the school must pay dollars to update the record.
Given the initially registered plans and the costs , determine how the users should choose their plans so that the total fee paid to the company (plan change costs plus pairwise charges) is as small as possible.
Input
The first line contains one positive integer .
The second line contains integers, the registered plans of users . Each number is 0 if the initial plan is A, or 1 if the initial plan is B.
The third line contains integers , the cost in dollars for each user to change plans.
The next lines contain the data flow table . The th line contains the -th integer (, ).
Output
Print a single integer, the minimum total amount in dollars that the school has to pay the company.
Constraints
, , .