Loading

P2080 增进感情(背包DP)

思路:将好感度x+y作为体积, 幸福度x-y作为作为价值, 然后就是一个经典的背包问题了。emmmmm,还可以特判一下,因为幸福度为0时就是最小了,没有必要看后面的了吧。

其实,我自己做的时候,沙雕的认为是每一对的幸福度的绝对值之和,原来是总的的绝对值。

 

// luogu-judger-enable-o2
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f;
int f[100001], tot;
struct node{
    int w, v;
}a[110];
bool cmp(node a, node b){
    return a.w > b.w;
}
int N, V, ans = INF;

int main(){
    cin >> N >> V;
    for (int i = 1; i <= N; ++i){
        int c, b;
        cin >> c >> b;
        a[i].v = b - c;
        a[i].w = c + b;
        if (c + b > 0)tot += a[i].w;
    }
    if (tot < V){ cout << -1 << endl; return 0; }
    memset(f, INF, sizeof(f));
    f[0] = 0;
    sort(a + 1, a + N + 1, cmp);
    for (int i = 1; i <= N; ++i){
        for (int j = tot; j >= a[i].w; --j){
            if (abs(f[j - a[i].w] + a[i].v) < abs(f[j])){
                f[j] = f[j - a[i].w] + a[i].v;
                if (f[j] == 0 && j >= V){
                    cout << 0 << endl;
                    return 0;
                }
            }
        }
    }

    for (int i = V; i <= tot; ++i)
    if (abs(f[i]) < ans)ans = abs(f[i]);
    if (ans == INF)cout << -1 << endl;
    else cout << ans << endl;

    return 0;
}

 

posted @ 2019-04-09 18:37  青山新雨  阅读(265)  评论(0编辑  收藏  举报