[codeforces888E]Maximum Subsequence

time limit per test : 1 second
memory limit per test : 256 megabytes

You are given an array a consisting of n n n integers, and additionally an integer m m m. You have to choose some sequence of indices b 1 ,   b 2 ,   . . . ,   b k ( 1   ≤   b 1   &lt;   b 2   &lt;   . . .   &lt;   b k   ≤   n ) b_1, b_2, ..., b_k (1 ≤ b_1 &lt; b_2 &lt; ... &lt; b_k ≤ n) b1,b2,...,bk(1b1<b2<...<bkn) in such a way that the value of is maximized. Chosen sequence can be empty.
Print the maximum possible value of ( ∑ 1 k a b i ) (\sum^k_1 {a_{b_i}}) (1kabi) m o d mod mod m m m.

Input

The first line contains two integers n n n and m ( 1   ≤   n   ≤   35 , 1   ≤   m   ≤   1 0 9 ) m (1 ≤ n ≤ 35, 1 ≤ m ≤ 10^9) m(1n35,1m109).
The second line contains n n n integers a 1 , a 2 , . . . , a n ( 1   ≤   a i   ≤   1 0 9 ) a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) a1,a2,...,an(1ai109).

Output
Print the maximum possible value of ( ∑ 1 k a b i ) (\sum^k_1 {a_{b_i}}) (1kabi) m o d mod mod m m m.

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 b = {1, 2} b=1,2, so the sum is equal to 7 7 7 (and that’s 3 3 3 after taking it modulo 4 4 4).
In the second example you can choose a sequence b   =   3 b = {3} b=3.

题意:
n n n个数字里面选任意个,使得他们的和对 m m m取模之后最大。输出这个最大值

题解:
折半搜索。先搜出前半段的所有和的结果,存在set里面,然后去后半段搜索的时候,假设当前状态的和取模后是 x x x,那么我们就在set里面找小于等于m-x-1的最大数字。(记得用*--upper_bound(x)

tips:
upper_bound找的是大于x的第一个。
lower_bound找的是大于等于x的第一个。

#include<bits/stdc++.h>
#define LiangJiaJun main
using namespace std;
int n,m,c[2];
int a[44][2];
int calc(int status,int r,int sit){
    int ret=0;
    for(int i=1;i<=r;i++){
        if(status&(1<<(i-1))){
            ret=(ret+a[i][sit])%m;
        }
    }
    return ret;
}
set<int>tr;
int w33ha(){
    tr.clear();
    int half=n/2;
    c[0]=half;
    c[1]=n-half;
    for(int i=1;i<=n;i++){
        int x;
        scanf("%d",&x);
        if(i<=half)a[i][0]=x;
        else a[i-half][1]=x;
    }
    int ans=0;
    for(int S=0;S<(1<<c[0]);S++){
        int now=calc(S,c[0],0);
        tr.insert(now);
    }
    for(int S=0;S<(1<<c[1]);S++){
        int now=calc(S,c[1],1);
        int G=(*--tr.upper_bound(m-now-1));
        ans=max(ans,G+now);
    }
    printf("%d\n",ans);
    return 0;
}
int LiangJiaJun(){
    while(scanf("%d%d",&n,&m)!=EOF)w33ha();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值