Question meaning:
Question solution: messing with +01 backpack. The
original question is about choosing among n people and choosing among m people. The sum of w must be equal. We can reverse the w in m.
If you directly follow the input dp, w is always positive and accumulates to 1e6, and the value range is too large. We use random_shuffle to randomize the position, so that we can probably ensure that the previous w sum floats around 0. If w is negative, just shift to the right. Here I took 40,000, and I passed it twice at random.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
int t, n, m, w, v;
struct node {
int w, v;
}a[22222];
ll dp[1111111];
void cmax(ll& x, ll y) {
if (y > x) x = y;
}
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &w, &v);
a[i] = {
w, v };
}
for (int i = n + 1; i <= n + m; i++) {
scanf("%d%d", &w, &v);
a[i] = {
-w, v };
}
n += m;
ll ans = 0;
random_shuffle(a + 1, a + n + 1);
random_shuffle(a + 1, a + n + 1);
memset(dp, -0x3f3f, sizeof(dp));
dp[40000] = 0;
for (int i = 1; i <= n; i++) {
if (a[i].w > 0) {
for (int j = 80000; j >= a[i].w; j--) cmax(dp[j], dp[j - a[i].w] + a[i].v);
}
else {
for (int j = a[i].w; j <= 80000; j++) cmax(dp[j], dp[j - a[i].w] + a[i].v);
}
cmax(ans, dp[40000]);
}
printf("%lld\n", ans);
}
return 0;
}