P17024 [ROI 2026 Day2] 火星背包 题解

· · 题解

有 n 件物品,第 i 件物品有奇怪度 w_i 和价值 c_i。

你要选择一个集合 S 使得 \sum_{i\in S}c_i\ge C,在此基础上使得 i\in S 的 w_i 按位或的值尽量小。

$1\le n\le 2\times 10^6,1\le K\le 22,0\le w_i<2^K,0\le c_i\le 10^9$。

感觉很妙啊。

就是第一想法肯定是从高位开始确定每一位,然后发现 ans_i 随着 i 增大一定是单调不增的。

所以在第 K 位 ans_{1}\sim ans_n 的值一定形如 \cdots 1111100000\cdots 的形式,然后递归到子区间,子区间依旧是这个形式。

考虑分治,令 Calc(dep,S,l,r) 表示当前在处理第 dep 位,当前或值为 S(S 由确定的前缀以及后缀全 1 组成),处理的区间为 [l,r]。

我们定义 S'=S\oplus 2^{dep},即尝试第 dep 位填 0。

对于固定的 S',令 F_{i}(S')=\sum_{j\le i,w_j\sube S'}c_j,则 F_i(S') 随着 i 增大单调不减,因此存在分界点 p 使得 i<p 的 F_{i}(S')<C,i\ge p 的 F_{i}(S')\ge C。

于是 l\sim p-1 的第 dep 位必须取 1,p\sim r 的第 dep 位必须取 0。

我们首先要算出 F_{l-1}(S'),然后逐个加入 l\sim r。

于是令 cnt_{dep,T} 表示 w_1\sim w_{l-1} 中满足在 >dep 的位数能被确定的前缀容纳,且 0\sim dep 位恰好等于 T 的 c_i 的和。

有 F_{l-1}(S')=\sum_{j<l,w_j\sube S'}c_j=\sum_{T=0}^{2^{dep}-1} cnt_T。

然后扫描 i=l\sim r,如果 w_i\sube S',那么 F_{i}(S')=F_{i-1}(S')+c_i,找到分界点 p。

然后准备递归到子区间 [l,p-1],此时因为 S 第 dep 位为 1,所以第 dep 位可以随便填,于是 \forall T\in [0,2^{dep}),有 cnt_{dep-1,T}=cnt_{dep,T}+cnt_{dep,T+2^{dep}}。

然后递归到 [p,r],初始有 cnt_{dep-1,T}=cnt_{dep,T},然后加入 [l,p-1] 中能被 S' 容纳的物品,只取 0\sim dep-1 位,有 cnt_{dep-1,w_i\& (2^{dep}-1)}\leftarrow cnt_{dep-1,w_i\& (2^{dep}-1)}+c_i。

当 dep<0 时令 \forall i\in [l,r],ans_{i}=S。

时间复杂度 \mathcal{O}(nk+k2^k)。

#include<bits/stdc++.h>
#define FL(i,a,b) for(int i=(a);i<=(b);i++)
#define FR(i,a,b) for(int i=(a);i>=(b);i--)
#define ll long long
using namespace std;
const int MAXN = 2e6 + 10;
const int MAXK = 22 + 1;
const int MR = (1<<22) + 10;

int n,K;
ll C,sum=0;
int W[MAXN],V[MAXN],ans[MAXN];
ll cnt[MAXK][MR];

void Solve(int dep,int S,int l,int r){
    if(l>r) return ;
    if(dep<0){
        FL(i,l,r) ans[i]=S;
        return ;
    }
    S^=(1<<dep);
    ll nw=0;
    FL(T,0,(1<<dep)-1) nw+=cnt[dep][T];
    int p=r+1;
    FL(i,l,r){
        if((W[i]|S)==S) nw+=V[i];
        if(nw>=C){
            p=i;
            break;
        }
    }
    if(dep) FL(T,0,(1<<dep)-1) cnt[dep-1][T]=cnt[dep][T]+cnt[dep][T|(1<<dep)];
    Solve(dep-1,S|(1<<dep),l,p-1);
    if(dep){
        FL(T,0,(1<<dep)-1) cnt[dep-1][T]=cnt[dep][T];
        FL(i,l,p-1) if((W[i]|S)==S) cnt[dep-1][W[i]&((1<<dep)-1)]+=V[i];
    }
    Solve(dep-1,S,p,r);
}

int main(){
    freopen("pack.in","r",stdin);
    freopen("pack.out","w",stdout);
    scanf("%d%d%lld",&n,&K,&C);
    FL(i,1,n) scanf("%d%d",&W[i],&V[i]);
    Solve(K-1,(1<<K)-1,1,n);
    FL(i,1,n){
        sum+=V[i];
        printf("%d\n",(sum<C?-1:ans[i]));
    }
}