博客园 首页 私信博主 显示目录 隐藏目录 管理

题解 CF1446A 【Knapsack】

题目大意

给你 \(n\) 个物体,体积为 \(w_i\) 。并且给你一个大小为 \(c\) 的背包。

要求你取若干个物品使得 : \(\lceil \frac{c}{2} \rceil \le \sum{w_i} \le c\)

并且输出取了哪些。

题解

考虑贪心。

排序后从大往小的地方去取。

如果当前取了会超过 \(c\) 就不取。

只要大于 \(\lceil \frac{c}{2} \rceil\) 就直接 \(break\)

这么证明这种做法是正确的?

我们只要找到一种满足条件的,他没要求总和最多,也没要求取的数最多。

所以你只要先去最大的,如果当前取了超过 \(c\) ,那么他就不能取。

就继续取小的,这样是没有后效的,因为如果你这样都不可以取,那么上面的更加不可以取了。

所以你只要从大往小去取,记得记录编号在排序,因为他要输出编号。

细节自己读下代码。

代码

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define Rep(x, a, b) for(int x = a; x <= b; ++ x)
#define Dep(x, a, b) for(int x = a; x >= b; -- x)
#define Next(i, x) for(int i = head[x]; i; i = e[i].nxt)
int read() {
    char c = getchar(); int f = 1, x = 0;
    while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); }
    while(c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
    return x * f;
}
const int maxn = 200010;
int p[maxn];
struct node {
    int a, id;
} e[maxn];
int cmp(node x, node y) {
    return x.a > y.a;
}
signed main() {
    int T = read();
    while(T --) {
        int n = read(), c = read(), cnt = 0, ans = 0, pla = -1;
        Rep(i, 1, n) e[i].a = read(), e[i].id = i;
        sort(e + 1, e + n + 1, cmp);
        Rep(i, 1, n) {
            ans += e[i].a;
            if(ans > c) {ans -= e[i].a; continue; }
            p[++ cnt] = e[i].id;
            if(ans >= ceil(1.0 * c / 2)) { pla = i; break;}
        }
        if(ans >= ceil(1.0 * c / 2) && ans <= c) {
            printf("%d\n", cnt);
            Rep(i, 1, cnt) printf("%d ", p[i]); puts("");
        }
        else puts("-1");
    }
    return 0;
}
posted @ 2020-11-22 13:40  Flash_plus  阅读(153)  评论(0编辑  收藏  举报