题解 CF730J 【Bottles】

· · 题解

这题其实就是一个简单的01背包问题

思路

f_{i,j,k}=max(f_{i-1,j,k},f_{i-1,j-1,k-b_i}+a_i)

代码讲解

#include<bits/stdc++.h>
using namespace std;
const int N=110;
int read(){
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        x=(x<<3)+(x<<1)+ch-'0';
        ch=getchar();
    }
    return x*f;
}
int n,f[N][N*N],sum,tot,ans1,ans2;
struct bottle{
    int a,b;
}b[N];
bool cmp(bottle a,bottle b){
    return a.b>b.b;
}
int main(){
    n=read();
    memset(f,-0x3f,sizeof(f));
    f[0][0]=0;
    for(int i=1;i<=n;i++)b[i].a=read(),sum+=b[i].a;//计算体积和
    for(int i=1;i<=n;i++)b[i].b=read();
    sort(b+1,b+n+1,cmp);
    while(sum>tot)tot+=b[++ans1].b;
    printf("%d ",ans1);
    for(int i=1;i<=n;i++)for(int j=ans1;j;j--)for(int k=tot;k>=b[i].b;k--)f[j][k]=max(f[j][k],f[j-1][k-b[i].b]+b[i].a);//这一段是 dp ,注意 j 和 k 是要倒序枚举的
    for(int i=sum;i<=tot;i++)ans2=max(ans2,f[ans1][i]);//体积为 sum 到 tot 的答案都是可以的
    printf("%d",sum-ans2);//最终答案
    return 0;
}