思路
先选前 大的数,记和为 。枚举一对值 ,把 加进去,看最多能凑多少。
设第 大数为 ,第 大数为 。记 为值 在前 大中出现的次数。
分类讨论
- 两个都在前 大里:不用替换,和是 。
- 一个在,一个不在:把不在的加进去,替换掉第 大。但如果留下的那个恰好是 且只出现了一次,踢了它自己就没了,所以得替换 。
- 两个都不在:踢掉第 大和第 大,换成 ,和是 。
实现
值域只有 ,直接枚举所有不同值对,用上面的规则算答案,最坏复杂度 。
注意 时异或值为 ,单独处理,且要保证这个值至少出现了两次。
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
int rd(){
int x=0;
char c=getchar_unlocked();
while(c<'0' || c>'9') c=getchar_unlocked();
while(c>='0' && c<='9') x=x*10+c-'0',c=getchar_unlocked();
return x;
}
int c[10001],a[1000005],p[1000005],t[10001],v[10001];
signed main(){
int n=rd(),k=rd(),id=1;
for(int i=0;i<n;i++) c[rd()]++;
for(int x=10000;x>=1;x--){
int y=c[x];
while(y--) a[id++]=x;
}
for(int i=1;i<=n;i++) p[i]=p[i-1]+a[i];
int vk=a[k],v1=a[k-1],g=0;
for(int x=10000;x>=1;x--){
if(c[x]>0) t[x]=g>=k?0:min(c[x],k-g);
g+=c[x];
}
int m=0,b=p[k],q=p[k-2],ans=b;
for(int x=1;x<=10000;x++)if(c[x]>0)v[m++]=x;
for(int i=0;i<m;i++){
int x=v[i],tx=t[x],cx=c[x];
if(cx>=2){
int u=tx>=2? 2:(tx==1?1:0),s;
if(u==2) s=b;
else if(u==1) s=b+x-((x==vk && tx==1)? v1:vk);
else s=q;
ans=max(ans,s);
}
for(int j=i+1;j<m;j++){
int y=v[j],z=x^y,ty=t[y],u=(tx?1:0)+(ty?1:0),s;
if(b+z<=ans) continue;
if(u==2) s=b;
else if(u==1){
int xx=tx?x:y,yy=tx?y:x;
s=b+yy-((xx==vk && t[xx]==1)? v1:vk);
}else s=q;
ans=max(ans,s+z);
}
}
cout<<ans<<'\n';
return 0;
}完结散花!