P2014 [CTSC1997] 选课

2 篇文章 0 订阅
1 篇文章 0 订阅

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了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值