2021台北ICPC Seesaw (背包)
- 问题转化为从A,B两组中分别取相同个数的东西的某一权值总和的最取次数
- fa/b[i][j][v] 表示前i个数,取j个,能否凑成体积v,f值就是0/1
- 注意控制合法状态,最后的枚举不要超过A,B的值域
#include<bits/stdc++.h>
//#include <bits/extc++.h>
using namespace std;
// using namespace __gnu_cxx;
// using namespace __gnu_pbds;
#define IOS ios::sync_with_stdio(false) ,cin.tie(0), cout.tie(0);
//#pragma GCC optimize(3,"Ofast","inline")
#define ll long long
#define li __int128_t
//#define int long long
const int N = 1e5 + 5;
const int M = 1e6 + 5;
const int mod = 1e9 + 7;
const ll LNF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
int a[105], b[105], cnta, cntb;
bool fa[105][105][5055], fb[105][105][5055];
void solve() {
cnta = cntb = 0;
memset(fa, 0, sizeof fa);
memset(fb, 0, sizeof fb);
int n, x; cin >> n;
int suma = 0, sumb = 0, A = 0, B = 0;
for ( int i = 1; i <= n; ++ i ) {
cin >> x;
if( x <= 2 ) b[ ++ cntb ] = i, B += i;
sumb += x * i;
}
for ( int i = 1; i <= n; ++ i ) {
cin >> x;
if( x <= 2 ) a[ ++ cnta ] = i, A += i;
suma += x * i;
}
if( suma == sumb ) {
cout << 0 << '\n'; return;
}
if( suma < sumb) {
cout << -1 << '\n'; return;
}
for ( int i = 0; i <= cnta; ++ i) fa[i][0][0] = 1;
for ( int i = 0; i <= cntb; ++ i) fb[i][0][0] = 1; //第二位是要控制合法状态,第一维不用
for ( int i = 1; i <= cnta; ++ i ) {
for ( int j = 1; j <= cnta; ++ j ) {
for ( int v = A; v >= 0; -- v ) {//要继承
if( v >= a[i] && fa[i - 1][j - 1][v - a[i]] )
fa[i][j][v] = fa[i - 1][j - 1][v - a[i]];
if( fa[i - 1][j][v] > 0)
fa[i][j][v] = fa[i - 1][j][v];//要继承
}
}
}
for ( int i = 1; i <= cntb; ++ i ) {
for ( int j = 1; j <= cntb; ++ j ) {
for ( int v = B; v >= 0; -- v ) { //要继承
if( v >= b[i] && fb[i - 1][j - 1][v - b[i]] )
fb[i][j][v] = fb[i - 1][j - 1][v - b[i]];
if( fb[i - 1][j][v] > 0)
fb[i][j][v] = fb[i - 1][j][v]; //要继承
}
}
}
int cha = suma - sumb;
for ( int i = 1; i <= min(cnta, cntb); ++ i ) {
int st = min(A, cha); //要在A,B值域内枚举
for ( int j = st; j >= 0; -- j ) {
if(cha - j > B) continue; // cha - j 会特别大,就越界了
if(fa[cnta][i][j] > 0 && fb[cntb][i][cha - j] > 0 ) {
cout << i << '\n';
return;
}
}
}
cout << -1 <<'\n';
}
int main() {
IOS
int t; cin >> t;
while( t -- ) solve();
return 0;
}