选课

AcWing-286-选课open in new window

分析

见《进阶指南》第291页。

实现

#include <iostream>
#include <cstring>
using namespace std;

const int N = 310;
struct edge {
    int to, next;
};
edge e[N];
int idx, head[N];
int n, m;
int w[N], f[N][N]; // w[0] 为 0

void add_edge (int u, int v) {
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx ++;
}
void dfs (int cur) {
    for (int j = 1; j <= m; ++ j) f[cur][j] = w[cur];
    for (int i = head[cur]; i != -1; i = e[i].next) {
        int to = e[i].to;
        dfs(to);
        for (int j = m; j >= 1; -- j)
            for (int k = 0; k <= j - 1; ++ k)
                f[cur][j] = max(f[cur][j], f[cur][j - k] + f[to][k]);
    }
}

int main () {
    memset(head, -1, sizeof(head));
    cin >> n >> m;
    for (int i = 1, p; i <= n; ++ i) {
        cin >> p >> w[i];
        add_edge(p, i);
    }

    ++ m; // 虚拟课程
    dfs(0);
    cout << f[0][m] << endl;
    return 0;
}
最后修改于: