P17024 [ROI 2026 Day2] 火星背包 题解
Iris_Aurora · · 题解
有
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$。
感觉很妙啊。
就是第一想法肯定是从高位开始确定每一位,然后发现
所以在第
考虑分治,令
我们定义
对于固定的
于是
我们首先要算出
于是令
有
然后扫描
然后准备递归到子区间
然后递归到
当
时间复杂度
#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]));
}
}