思路
一开始想到的是分组背包,但是没有合理利用数组的单调性,所以TLE了
关键结论:对于任意两个数组和,假如从取到且,从取到且,假设和都没取完,那么这种方案还不如不取,直接贪心地把取完,所以选取的方案最多只能有一个数组没有取完,否则一定有更优的方案
考虑线段树分治,如图:
当前分治到节点,假设没有取完的数组在红色中,那么蓝色中的所有数组肯定要么取完,要么不取,所以对蓝色进行一次背包,复制结果保存在中
当接下来要从红色走到绿色中时,可以直接把中已经计算完的调出来,再对橙色进行背包,相当于对橙色和蓝色一起进行
如果要从红色走到橙色中时,再次把调出来,再对绿色进行背包
这样做相当于每层只有的复杂度,一共就是
代码
#include<bits/stdc++.h>
#define min(x,y) ((x>y)?(y):(x))
#define max(x,y) ((x>y)?(x):(y))
using namespace std;
typedef long long ll;
const int N = 3e3 + 10, inf = 2e9;
ll n, m, k, a[N][N], cnt[N], f[N], ans, t[N << 2][N];
ll read(){
ll x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -f; ch = getchar();}
while(ch >= '0' && ch <= '9') {x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar();}
return x * f;
}
void query(int x, int l, int r){
if(l == r){
for(int i = 0; i <= cnt[l]; i++){
ans = max(ans, a[l][i] + f[k - i]);
}
return;
}
int mid = l + r >> 1;
for(int i = 0; i <= k; i++) t[x][i] = f[i];
for(int i = mid + 1; i <= r; i++){
for(int j = k; j >= cnt[i]; j--){
f[j] = max(f[j], f[j - cnt[i]] + a[i][cnt[i]]);
}
}
query(x << 1, l, mid);
for(int i = 0; i <= k; i++) f[i] = t[x][i];
for(int i = l; i <= mid; i++){
for(int j = k; j >= cnt[i]; j--){
f[j] = max(f[j], f[j - cnt[i]] + a[i][cnt[i]]);
}
}
query(x << 1 | 1, mid + 1, r);
}
int main(){
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
// ios::sync_with_stdio(false);
// cin.tie(0);
// cout.tie(0);
n = read(), k = read();
for(int i = 1; i <= n; i++){
m = read();
for(int j = 1; j <= m; j++){
if(j <= k) a[i][j] = a[i][j - 1] + read();
else read();
}
cnt[i] = min(m, k);
}
query(1, 1, n);
printf("%lld", ans);
// fclose(stdin);
// fclose(stdout);
return 0;
}