杭电多校训练 dp 背包问题

I love exam

有依赖关系的背包问题

#include<bits/stdc++.h>

#define N 500
using namespace std;
typedef long long ll;
int n, m;
map<string, int> mp;
string s;
int f[109][109], dp[1009][15], mx[52][1009];

inline ll rd() {
    ll x = 0;
    char c = getchar();
    bool f = 0;
    while (!isdigit(c)) {
        if (c == '-')f = 1;
        c = getchar();
    }
    while (isdigit(c)) {
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }
    return f ? -x : x;
}

struct node {
    int x, y;
};
vector<node> vec[N];

void solve() {
    n = rd();
    char s1[20];
    for (int i = 1; i <= n; ++i) {
        cin >> s1;
        mp[s1] = i;         //将课程数字化
    }
    m = rd();
    int x, y;
    for (int i = 1; i <= m; ++i) {
        cin >> s1;
        int id = mp[s1];
        x = rd();
        y = rd();
        node no;
        no.x = x, no.y = y;
        vec[id].push_back(no);
    }
    int t = rd();
    int p = rd();


    memset(f, 0x3f, sizeof(f));
    memset(dp, -0x3f, sizeof(dp));
    memset(mx, 0, sizeof(mx));

    //遍历每门课,每个材料
    for (int i = 1; i <= n; ++i) {
        f[i][0] = 0;
        for (int j = 0; j < vec[i].size(); ++j)
            for (int k = 100; k >= vec[i][j].x; --k)
                f[i][k] = min(f[i][k], f[i][k - vec[i][j].x] + vec[i][j].y);//选择 消耗成绩 付出天数 成绩为k时最少消耗的天数


        for (int k = 1; k <= 100; ++k)
            if (f[i][k] <= 500) mx[i][f[i][k]] = max(mx[i][f[i][k]], k);
    }
    dp[0][0] = 0;
    for (int i = 1; i <= n; ++i) {
        for (int j = t; j >= 1; --j) {
            for (int k = p; k > 0; --k)
                dp[j][k] = dp[j][k - 1];
            dp[j][0] = -1e9;
            for (int k = 0; k <= p && k <= n; ++k)
                for (int l = 1; l <= f[i][100] && l <= j; ++l) {
                    //如果有一科 每一门都不能及格,那么应该没有dp[j][0];
                    if (mx[i][l] >= 60)dp[j][k] = max(dp[j - l][k] + mx[i][l], dp[j][k]);
                    else if (k)dp[j][k] = max(dp[j - l][k - 1] + mx[i][l], dp[j][k]);
                }
        }
        dp[0][0] = -1e9;
    }
    int ans = -1;
    for (int i = 1; i <= t; ++i) {
        for (int j = 0; j <= p; ++j) {
            ans = max(ans, dp[i][j]);
        }
    }
    mp.clear();
    for (int i = 1; i <= n; ++i)vec[i].clear();
    cout << ans << endl;

}

int main() {
    int T = rd();
    while (T--)solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值