[CF888 E]Maximum Subsequence(meet in middle)

题目:

我是超链接

题意:

有n个数,求从中选任意个数加和对k取模后的最大值。

题解:

有一个事情就是如果a < mod && b< mod && a+b>mod ,那么(a+b)%mod一定是小于a,b的
显然可得了

那么这道题目就是双向搜索,然后凑数就是如果两个数相加>=k就显然不是最优答案,r- -,找到一个l+r < k的就是对于l来说最大的可凑r是谁,就不用往下继续了。

双向指针可以解决,但不要忘记原本的数也是要比较一下大小

代码:

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int N=2000000;
int n,k,mb,tmp1[N],tmp2[N],sum1,sum2,a[N],ans;
void dfs(int t,int tot,int *tmp,int &sum)
{
    tot%=k;
    if (t>mb) {tmp[++sum]=tot;ans=max(ans,tot); return;}
    for (int i=0;i<=1;i++) dfs(t+1,tot+i*a[t],tmp,sum);
}
void work()
{
    sort(tmp1+1,tmp1+sum1+1);
    sort(tmp2+1,tmp2+sum2+1);
    int l=1,r=sum2;
    for (;l<=sum1 && r>=1;l++)
    {
        while (tmp1[l]+tmp2[r]>=k && r>0) r--;
        ans=max(ans,tmp1[l]+tmp2[r]);   
        while (tmp1[l]==tmp1[l+1] && l<sum1) l++;
    }
}
int main()
{
    scanf("%d%d",&n,&k);
    for (int i=1;i<=n;i++) scanf("%d",&a[i]),a[i]%=k;
    mb=n/2;
    dfs(1,0,tmp1,sum1);
    mb=n;
    dfs(n/2+1,0,tmp2,sum2);
    work();
    printf("%d",ans);
}

猜你喜欢

转载自blog.csdn.net/blue_cuso4/article/details/80854610