这题想起来挺简单的,两三分钟就出结论了,写起来也快,结果前几发提交用了I64d,卡了好久
对于答案x,最后的决策一定是取奇数个奇数和任意个偶数组成的,为了使答案最大,当奇数的个数和偶数的个数确定时,我们取最大的若干个。
将奇数取出来降序排序,将偶数取出来降序排序,倘若我们此时选择了p1的奇数,p2的偶数
若要增加奇数的个数,减少偶数的个数,就将p1+=2,p2-=2(维护总数奇数的性质),反复操作时候发现,所加的数越来越小,所减的数越来越大,即导数单调下降。
可以将答案的函数抽象成单峰函数,对于每个答案可以三分获得答案,但显然1e6的数据过不了
考虑当x-1答案为p1,p2时,将p1-=2,p2+=1,继续反复上述操作即可,正确性易证(可以理解为撤销了之前的一步操作,严格的证明也是相当简单的)
注意在移动p1,p2的过程中,全程要注意p1,p2是否合法
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 1000050
using namespace std;
typedef long long LL;
bool cmp(int p1,int p2) { return p1>p2; }
int x[N],a[N],b[N],cnta,cntb;
LL ans[N],sum_a[N],sum_b[N];
int n,m;
inline LL calc(int p1,int p2) { return sum_a[p1] + sum_b[p2]; }
int main() {
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&x[i]);
for (int i=1;i<=n;i++)
if (x[i]&1)
a[++cnta] = x[i];
else
b[++cntb] = x[i];
sort(a+1,a+cnta+1,cmp); sort(b+1,b+cntb+1,cmp);
for (int _=1;_<=cnta;_++) sum_a[_] = sum_a[_-1] + 1LL * a[_];
for (int _=1;_<=cntb;_++) sum_b[_] = sum_b[_-1] + 1LL * b[_];
memset(ans,255,sizeof(ans));
int p1=-1 , p2=1;
for (int _=1;_<=n;_++) {
p1 += 2 , p2 -= 1;
while (p1 > cnta) p1-=2 , p2+=2;
while (p2 < 0 ) p1-=2 , p2+=2;
if (p1 > cnta || p2 > cntb || p1 < 0 || p2 < 0) continue;
while (p1-2 >= 1 && p2+2 <= cntb && calc(p1-2,p2+2) > calc(p1,p2))
p1 -= 2 , p2 += 2;
ans[_] = calc(p1,p2);
}
scanf("%d",&m);
while (m--) { int q; scanf("%d",&q); printf("%lld\n",ans[q]); }
return 0;
}