Algorithm study membership
Time limit2sMemory limit512 MB
Choose two algorithm types for each of N members in a mentor tree so every team (a node plus its children) can assign distinct types to its members, minimizing total teaching cost.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Tree, Greedy, Bit manipulation
- Solved
- No attempts yet
Problem
An algorithm study group works through algorithm problems together. The group has N members, numbered 0 to N-1 in the order they joined.
Member 0 is the only member without a mentor. Every other member has exactly one mentor. The mentor of member i is member , and because member 0 has no mentor. A mentor must have joined the group before the member, so for every i with .
The organizer of the group decided to teach algorithms to all members. The group splits the algorithms used in problem solving into M types, numbered 1 to M. Teaching type i to one person costs won. Each member has to take two classes, and nobody can take the same type twice. After the classes, a member can solve every problem that belongs to the two types they learned, and cannot solve any problem outside those two types.
Every member has to form one team with themselves as the leader, so N teams are formed. The team led by member i consists of member i and the members whose mentor is member i, that is, every j with . If and , then k does not belong to the team led by member i.
A team qualifies for a programming contest when the conditions below hold.
- Every member of the team can solve problems.
- When the team members each pick one algorithm type to solve, a state with no overlap must be possible.
Each team is checked on its own, so one person may pick different types in different teams. A team that qualifies is called a good team.
Write a program that finds the minimum cost of choosing the two types to teach each member so that every team is a good team.
Input
The first line contains N and M. (, )
The second line contains N integers through in order. (, and for i with )
The third line contains M integers through in order. ()
Output
Print the minimum cost of teaching that makes every team a good team on the first line.
If no plan makes every team a good team, print -1.
Hint
In a team of k members, the k members have to pick k different types. So the types learned by those members must cover at least k different types, and beyond that, the members must be able to take one type each without any overlap.
A team with a single member is always a good team. If the group has only one member, teaching the two cheapest types costs the least.