P2080 增进感情(背包DP)

时间:2023-03-09 16:29:55
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[], tot;
struct node{
int w, v;
}a[];
bool cmp(node a, node b){
return a.w > b.w;
}
int N, V, ans = INF; int main(){
cin >> N >> V;
for (int i = ; i <= N; ++i){
int c, b;
cin >> c >> b;
a[i].v = b - c;
a[i].w = c + b;
if (c + b > )tot += a[i].w;
}
if (tot < V){ cout << - << endl; return ; }
memset(f, INF, sizeof(f));
f[] = ;
sort(a + , a + N + , cmp);
for (int i = ; 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] == && j >= V){
cout << << endl;
return ;
}
}
}
} for (int i = V; i <= tot; ++i)
if (abs(f[i]) < ans)ans = abs(f[i]);
if (ans == INF)cout << - << endl;
else cout << ans << endl; return ;
}