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 ≤ 35, 1 ≤ m ≤ 109).
The second line contains n integers a1, a2, ..., 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}.
AC code
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n,m;
vector<int> A,X,Y;
void gen(int l, int r, vector<int> &X)
{
X.push_back(0);
for (int i=l; i<=r; ++i)
{
int s = X.size();
for (int x=0; x<s; ++x)
X.push_back((A[i]+X[x])%m);
}
}
int main()
{
cin >> n >> m;
A.resize(n);
for (int i=0; i<n; ++i)
cin >> A[i];
int mid = n/2;
gen(0,mid,X);
gen(mid+1,n-1,Y);
sort(Y.begin(),Y.end());
int res = 0;
for (auto ix=X.begin(); ix!=X.end(); ++ix)
res = max(res,*ix + *(upper_bound(Y.begin(),Y.end(),m-1-*ix)-1));
cout << res << endl;
return 0;
}
最大子序列和问题
本文介绍了一个关于寻找整数数组中特定子序列的问题,该子序列使得其元素和除以给定整数后的余数最大化。文章提供了一个解决此问题的C++实现代码示例,该算法采用两阶段选择子序列的方法并利用排序和二分查找来提高效率。
410

被折叠的 条评论
为什么被折叠?



