Codeforces-888E:Maximum Subsequence(思维)

来源:互联网 发布:实名淘宝号购买 编辑:程序博客网 时间:2024/05/21 08:05

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 45 2 4 1
output
3
input
3 20199 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;}


原创粉丝点击