#P2014. Course Selection for Maximum Credits

    ID: 15296 Type: Default 1000ms 256MiB

Course Selection for Maximum Credits

Course Selection for Maximum Credits

In a university, each student must earn a certain number of credits by selecting courses from a large set. There are N courses; each course has an associated credit value. Additionally, every course may have at most one direct prerequisite. If course a is the prerequisite of course b, then course a must be completed before course b can be taken.

A student must select exactly M courses to study, while ensuring that if a course is chosen, its prerequisite (and recursively, all of its prerequisites) are also chosen. The objective is to maximize the sum of credits earned by the selected courses.

The problem can be summarized as follows:

  • There are N courses numbered from 1 to N.
  • Each course i has a credit value a_i.
  • Each course also has either one direct prerequisite or none. The prerequisite of course i is given as an integer. A value of 0 indicates that the course has no prerequisite.
  • If course x is a prerequisite for course y, then selecting course y forces course x to be selected as well (and recursively, all ancestors in the prerequisite chain must be selected).
  • Select exactly M courses such that the prerequisite condition holds and the total credit sum is maximized.

Mathematically, if selecting course i contributes a_i credits and if course j is a prerequisite for i (denoted by j \rightarrow i), then a valid selection S (with |S| = M) must satisfy:

[ \forall i \in S, \text{ if there exists } j \text{ with } j \rightarrow i, \text{ then } j \in S. ]

The goal is to maximize:

[ \text{Maximize } \sum_{i \in S} a_i \quad \text{subject to } |S| = M \text{ and valid prerequisites conditions.} ]

</p>

inputFormat

The input consists of three lines:

  1. The first line contains two integers N and M (1 ≤ M ≤ N), representing the number of courses and the number of courses to select, respectively.
  2. The second line contains N space-separated integers where the i-th integer represents the credit value of course i.
  3. The third line contains N space-separated integers. The i-th integer indicates the direct prerequisite of course i; a value of 0 means that course i has no prerequisite.

outputFormat

Output a single integer which is the maximum total credits that can be earned by selecting exactly M courses while satisfying the prerequisite conditions.

sample

3 2
3 5 7
0 1 1
10