Blobs' Exhibition opentrains

贪心算法解决背包问题
本文介绍了一种使用贪心算法解决背包问题的方法。通过将物品按价值密度排序,并利用multiset和lowerbound查找合适的位置放置物品,实现近似最优解。算法的时间复杂度为O(n log n)。

这里写图片描述

这题就是个贪心题
通过对价值排序,然后从高到低,每次找一个尽量小的能放得下的位置放置就好了
我是用了multiset和lowerbound来查找
时间是nlogn的

#include <bits/stdc++.h>
#include <set>
#include <algorithm>
using namespace std;

struct Node {
    int v, w, index;
    Node() {}
    Node(int vv, int ww, int ii): v(vv), w(ww), index(ii) {}
    bool operator<(const Node &other) const {
        if (v > other.v) return true;
        if (v < other.v) return false;
        return w < other.w;
    }
};

struct NNode {
    int w, index;
    NNode() {}
    NNode(int ww, int ii): w(ww), index(ii) {}
    bool operator<(const NNode &other) const {
        return w < other.w;
    }
};

const int maxn = 10010;
multiset<NNode> s;
int f[maxn];
Node a[maxn];
int n, m, x;

int main() {
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);

    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &x);
        s.insert(NNode(x, i));
    }
    for (int i = 1; i <= m; i++) {
        scanf("%d %d", &a[i].v, &a[i].w);
        a[i].index = i;
    }
    sort(a+1, a+1+m);
    for (int i = 1; i <= m; i++) {
        multiset<NNode>::iterator k = s.lower_bound(NNode(a[i].w, 1));
        if (k != s.end()) {
            f[(*k).index] = a[i].index;
            s.erase(k);
        }
    }
    for (int i = 1; i < n; i++) printf("%d ", f[i]);
    printf("%d\n", f[n]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值