题意
有n件商品,选出其中的k个,要求它们的总价为奇数,求最大可能的总价。
n,m<=1000000,1<=价格<=10^9
分析
考虑如何从选k个数的状态转移到选k+1个数的状态。可以假如一个偶数,也可以假如两个奇数同时在原来已选的数中删掉一个偶数。而如果这两种情况都不满足,则选k+1个物品的情况无解。
我们可以用四个单调栈来维护这个过程。
一开始WA是因为没有想到若k+1不行的话不代表k+2不行。我们可以通过加入两个奇数来转移到k+2的状态。
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=1000005;
int a1[N],a2[N],b1[N],b2[N],top1,top2,top3,top4,n,m;
LL ans[N];
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*10+ch-'0';ch=getchar();}
return x*f;
}
int main()
{
n=read();
for (int i=1;i<=n;i++)
{
int x=read();
if (x&1) a1[++top1]=x;
else b1[++top2]=x;
}
sort(a1+1,a1+top1+1);sort(b1+1,b1+top2+1);
if (!top1) top2=0;
a2[++top3]=a1[top1];top1--;
ans[1]=a2[top3];
for (int i=2;i<=n;i++)
{
if ((top1<2||!top4)&&!top2)
{
if (top1<2) break;
i++;
ans[i]=ans[i-2]+a1[top1]+a1[top1-1];
a2[++top3]=a1[top1];top1--;a2[++top3]=a1[top1];top1--;
continue;
}
if (!top2)
{
ans[i]=ans[i-1]+a1[top1]+a1[top1-1]-b2[top4];
b1[++top2]=b2[top4];top4--;
a2[++top3]=a1[top1];top1--;a2[++top3]=a1[top1];top1--;
}
else if (top1<2||!top4)
{
ans[i]=ans[i-1]+b1[top2];
b2[++top4]=b1[top2];top2--;
}
else
{
LL w1=a1[top1]+a1[top1-1]-b2[top4],w2=b1[top2];
if (w1>w2) ans[i]=ans[i-1]+w1,a2[++top3]=a1[top1],top1--,a2[++top3]=a1[top1],top1--,b1[++top2]=b2[top4],top4--;
else ans[i]=ans[i-1]+w2,b2[++top4]=b1[top2],top2--;
}
}
m=read();
while (m--)
{
int x=read();
if (!ans[x]) puts("-1");
else printf("%lld\n",ans[x]);
}
return 0;
}