#Q156. 「一本通 5.2 例 2」选课
「一本通 5.2 例 2」选课
Description
Original source: CTSC 1997
Universities implement a credit system. Each course has a certain number of credits, and students can earn the corresponding credits by enrolling in and passing the course. A student's final credit total is the sum of the credits from all the courses they have taken.
Every student is required to select a specified number of courses. Some courses can be taken directly, while others require foundational knowledge and can only be taken after completing certain prerequisite courses. For example, Data Structures can only be taken after completing Advanced Programming Languages. We refer to Advanced Programming Languages as the prerequisite course for Data Structures. Each course has at most one direct prerequisite course. Two courses may share the same prerequisite course. For ease of reference, each course is assigned a unique course number, starting from .
Here is an example:
| Course No. | Prerequisite Course No. | Credits |
|---|---|---|
| None | ||
| None | ||
In the example above, Course No. is the prerequisite for Course No. , meaning that to take Course No. , Course No. must have been completed. Similarly, to take Course No. , both Course No. and Course No. must have been completed.
Students cannot take all the courses offered by the university, so they must decide which courses to take upon enrollment. The total number of courses each student can select is predetermined. Your task is to find a course selection plan that maximizes the total credits earned while adhering to the prerequisite rules. Assume there are no scheduling conflicts between courses.
Input Format
The first line of input contains two positive integers and , representing the number of available courses and the number of courses that can be selected, respectively.
The next lines each describe a course, with course numbers ranging from to . Each line contains two numbers: the prerequisite course number (or if there is none) and the credits for that course.
Adjacent values are separated by spaces.
Output Format
Output a single line with the total credits earned from the selected courses.
Sample 1
7 4
2 2
0 1
0 4
2 1
7 1
7 6
2 2
13
Constraints & Notes
, and the credits for each course do not exceed .