zoukankan      html  css  js  c++  java
  • 洛谷P1757 通天之分组背包 题解 分组背包

    题目链接:https://www.luogu.com.cn/problem/P1757

    解题思路:

    所谓分组背包,就是将物品分组,每组的物品相互冲突,最多只能选一个物品放进去。

    这种题怎么想呢?其实是从「在所有物品中选择一件」变成了「从当前组中选择一件」,于是就对每一组进行一次 0-1 背包就可以了。

    示例代码:

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 1010;
    struct Node {
        int c, v;
        Node() {};
        Node(int _c, int _v) { c = _c; v = _v; }
    };
    map<int, vector<Node> > groups;
    int n, m, f[maxn];
    int main() {
        cin >> m >> n;
        for (int i = 0; i < n; i ++) {
            int a, b, c;
            cin >> a >> b >> c;
            groups[c].push_back(Node(a, b));
        }
        for (map<int, vector<Node> >::iterator it = groups.begin(); it != groups.end(); it ++) {
            vector<Node> group = it->second;
            int sz = group.size();
            for (int i = m; i >= 0; i --) {
                for (int j = 0; j < sz; j ++) {
                    int c = group[j].c, v = group[j].v;
                    if (i >= c) f[i] = max(f[i], f[i-c] + v);
                }
            }
        }
        cout << f[m] << endl;
        return 0;
    }
    
  • 相关阅读:
    JS 中 this 关键字详解
    Excel 文本函数
    Excel 日期和时间函数
    Excel引用和数学函数
    Excel-查找函数
    Excel-统计函数
    数据分析-业务知识
    Excel-逻辑函数
    Excel-基本操作
    电商数据分析总结
  • 原文地址:https://www.cnblogs.com/quanjun/p/13639666.html
Copyright © 2011-2022 走看看