拯救小矮人
思路: 贪心 + dp
首先贪心按身长加手长排序, 也就是让最难出去的先出去
但也有可能有人手短身子长, 那他奉献自己可能更优
所以在加个背包dp
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 2005;
const int H = 100500;
int dp[H], n, h; // dp[i] 表示出去i个人最高的高度
struct node{
int a, b;
bool operator < (const node &i) const {
return a + b < i.a + i.b;
}
}p[N];
int read(void) {
int x = 0; char c = getchar();
while (!isdigit(c)) c = getchar();
while (isdigit(c)) {
x = (x << 3) + (x << 1) + c - '0';
c = getchar();
}
return x;
}
int main() {
n = read();
for (int i = 1;i <= n; i++) p[i].a = read(), p[i].b = read();
h = read();
sort(p + 1, p + n + 1);
for (int i = 1;i <= n; i++) dp[i] = -0x3f3f3f3f, dp[0] += p[i].a;
// 每个人的体积为1, 价值为a
for (int i = 1;i <= n; i++)
for (int j = i;j >= 1; j--)
if (dp[j-1] + p[i].b >= h)
dp[j] = max(dp[j], dp[j-1] - p[i].a);
for (int i = n;i >= 0; i--)
if (dp[i] >= 0) {
cout << i << endl;
return 0;
}
return 0;
}