Codeforces-888E:Maximum Subsequence(思维)

E. Maximum Subsequence
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, b2, ..., bk (1 ≤ b1 < b2 < ... < bk ≤ n) in such a way that the value of  is maximized. Chosen sequence can be empty.

Print the maximum possible value of .

Input

The first line contains two integers n and m (1 ≤ n ≤ 351 ≤ m ≤ 109).

The second line contains n integers a1a2, ..., an (1 ≤ ai ≤ 109).

Output

Print the maximum possible value of .

Examples
input
4 4
5 2 4 1
output
3
input
3 20
199 41 299
output
19
Note

In the first example you can choose a sequence b = {1, 2}, so the sum  is equal to 7 (and that's 3 after taking it modulo 4).

In the second example you can choose a sequence b = {3}.


思路:如果n<=20,可以考虑状态压缩,但n>=35。那么可以考虑把n个数分为2个部分来状态压缩,然后用vector<int>c储存第一部分各个状态模m后的值,然后枚举第二部分各个状态模m后的值y,那我们可以在c中二分查找m-y-1,如果找不到,可以考虑比m-y-1小的最大的数和比m-y-1大的最大的数,这样就能保证答案尽可能的靠近m-1。

#include<bits/stdc++.h>
using namespace std;
__int64 a[40],b[40],n,m;
vector<__int64>c;
__int64 aget(__int64 x)
{
    __int64 ans=0;
    for(__int64 i=0;i<n/2;i++,x/=2)if(x%2)ans+=a[i];
    return ans%m;
}
__int64 bget(__int64 x)
{
    __int64 ans=0;
    for(__int64 i=0;i<n-n/2;i++,x/=2)if(x%2)ans+=b[i];
    return ans%m;
}
int main()
{
    __int64 ans=0;
    scanf("%I64d%I64d",&n,&m);
    for(__int64 i=0;i<n/2;i++)scanf("%I64d",&a[i]),ans=max(ans,a[i]%m);
    for(__int64 i=0;i<n-n/2;i++)scanf("%I64d",&b[i]),ans=max(ans,b[i]%m);
    for(__int64 i=0;i<(1<<(n/2));i++)c.push_back(aget(i));
    sort(c.begin(),c.end());
    for(__int64 i=0;i<(1<<(n-n/2));i++)
    {
        __int64 y=bget(i);
        ans=max(ans,y);
        __int64 x=lower_bound(c.begin(),c.end(),m-y-1)-c.begin();
        if(c.size()>0)
        {
            if(x>=0&&x<c.size())ans=max(ans,(y+c[x])%m);
            if(x>0)ans=max(ans,(y+c[x-1])%m);
            ans=max(ans,(y+c[c.size()-1])%m);
        }
    }
    cout<<ans<<endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值