In college, some courses has prerequisite, in this question every courses either has one prerequisite or no prerequisite.
For simplying the question, we consider 0 is the father node of those courses have no prerequisite. The advantage of this operation is to connect all the courses and generate a tree.
If we don't consider 0 as a father node, the graph would be a forest. It is pretty annoying when we solve it with dynamic programming.
After adding 0 as a father node of those courses have no prerequisite, we just need to solve a simple backpack problem.
Let's consider f(i, j) represent choose j courses under the root node i and the value is the maximum credits you can get.
It is almost the same with other backpack problem, the only different thing is we need to enumerate the courses under different roots.
the transfer formula is f(i, j) = max( f(i, j) , f(i's son node, k) + f(i, j - k)))
if you visulize it, it just cut off the tail of a selected courses link and change it to other tail or abandon it and choose other new course.
below is a demonstration of how the transfer function works.
About correctness, as we update the dp array from backward, and from smaller to bigger, we can ensure that our calculation are all legal.
Code:
#include <iostream>
#include <vector>
using namespace std;
int n, m;
int f[356][356];
vector<int> edge[350];
void dp(int curt){
for(auto a : edge[curt]){
int to = a;
dp(to);
for(int j = m + 1; j >= 1; j--){
for(int k = 0; k < j; k++){
f[curt][j] = max(f[curt][j], f[to][k] + f[curt][j - k]);
}
}
}
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
int u, w;
cin >> u >> w;
f[i][1] = w;
edge[u].push_back(i);
}
dp(0);
cout << f[0][m + 1];
return 0;
}
所以你學到什麼?
首先,見到限制選m門課,就要想到背包相關,把課程關係畫出來,就知道是樹上dp了。