Title Description
Each student, in order to achieve a certain credits must be selected from the many courses at the university to study in some courses, some courses must be before some of the courses in the curriculum, such as mathematics always learn before any other courses. There are N of courses, each course there are credits for each course or not there is a direct Prerequisite (if the course is a course that only Prerequisite b of a finished school curriculum, in order to learn the course b). These courses where a student choose courses from the M door and asked him to get the maximum credit is how much?
Input Format
The first line has two integers N, M separated by a space. (1 <= N <= 300,1 <= M <= 300)
The next N rows, the first row I + 1 and Si comprising two integers ki, ki represents a direct Prerequisite the course of I, I, Si represents the course credits. If ki = 0 indicates no direct Prerequisite (1 <= ki <= N, 1 <= si <= 20).
Output Format
Only one line, choose M courses maximum score.
Sample input and output
7 4 2 2 0 1 0 4 2 1 7 1 7 6 2 2
13
Solution: backpack tree packet DP, see Code
#include <the iostream> #include <algorithm> #include <Queue> #include <the cmath> #include <CString> #include <the cstdlib> #include <cstdio> the using namespace STD; const int N = 1003 ; int n-, m, F [N] [N], head [N], CNT, FA; // F [i] [j] i is represented in the sub-tree root node j is selected to obtain the highest credit course struct Edge { int to , Next; } E [N]; void the Add ( int from , int to) { CNT ++; E [CNT] .to = to; E [CNT] .next }head = [ from ]; head [ from ] = CNT; } void DP ( int U) { for ( int I = head [U]; I; I = E [I] .next) { // cycle child node int V = E [I] .to; DP (V); for ( int J = m + . 1 ; J> = . 1 ; J,) // loop current volume backpack, elective number of gates for ( int K = 0 ; K <J ; K ++) // number of cycles deeper Course gate subtree, i.e., the group of articles f [u] [j] = max (f [u] [j], f [v] [k] + f [u] [ J- K]); } int main () { freopen("2014.in","r",stdin); freopen("2014.out","w",stdout); scanf("%d %d",&n,&m); for(int i=1;i<=n;i++){ scanf("%d %d",&fa,&f[i][1]); add(fa,i); } dp(0); printf("%d\n",f[0][++m]); return 0; }