time limit per test : 1 second
memory limit per test : 256 megabytes
You are given an array a consisting of nnn integers, and additionally an integer mmm. You have to choose some sequence of indices b1, b2, ..., bk(1 ≤ b1 < b2 < ... < bk ≤ n)b_1, b_2, ..., b_k (1 ≤ b_1 < b_2 < ... < b_k ≤ n)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 (∑1kabi)(\sum^k_1 {a_{b_i}})(∑1kabi) modmodmod mmm.
Input
The first line contains two integers nnn and m(1 ≤ n ≤ 35,1 ≤ m ≤ 109)m (1 ≤ n ≤ 35, 1 ≤ m ≤ 10^9)m(1 ≤ n ≤ 35,1 ≤ m ≤ 109).
The second line contains nnn integers a1,a2,...,an(1 ≤ ai ≤ 109)a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9)a1,a2,...,an(1 ≤ ai ≤ 109).
Output
Print the maximum possible value of (∑1kabi)(\sum^k_1 {a_{b_i}})(∑1kabi) modmodmod mmm.
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, 2b = {1, 2}b = 1, 2, so the sum is equal to 777 (and that’s 333 after taking it modulo 444).
In the second example you can choose a sequence b = 3b = {3}b = 3.
题意:
从nnn个数字里面选任意个,使得他们的和对mmm取模之后最大。输出这个最大值
题解:
折半搜索。先搜出前半段的所有和的结果,存在set里面,然后去后半段搜索的时候,假设当前状态的和取模后是xxx,那么我们就在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;
}