E. Maximum Subsequence (meet-in-the-middle)

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 indicesb1, 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
Copy
4 4
5 2 4 1
output
Copy
3
input
Copy
3 20
199 41 299
output
Copy
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}.


转自题解:

Let's consider the naive solution in O(2n) or O(2n·n). Iterate over all subsets of original set, calculate sums and take maximum of them modulo m.

Now we can use meet-in-the-middle technique to optimize it to . Preprocess the first  elements naively and push sums modulo m to some array. After this process the second half with following algorithm.

Take sum of the set and find the greatest total sum of current and some sum in the array. As any sum of two numbers less than m can go no greater than 2m, we can consider just two values: the greatest number in array and the greatest number less thanm - currentSum in the array. This can be found by binary search over sorted array.

Overall complexity: .

参考代码:

#include
using namespace std;
#define ll long long
#define rep(i,a,n) for(int i=(a);i<(n);++i)
#define per(i,a,n) for(int i=(n-1);i>=(a);--i)
#define pb push_back
const int Inf=1e9;
#define N 1000010
#define M 26
void dfs(int *a,int i,int n,int tot,vector&sum,int mod){
    if(i>=n){
        cout<>n>>m){
        vectorsum1,sum2;
        rep(i,0,n) cin>>a[i],a[i]%=m;
        dfs(a,0,n/2,0,sum1,m);
        dfs(a,n/2,n,0,sum2,m);
        sort(sum1.begin(),sum1.end());
        sort(sum2.begin(),sum2.end());
        int ans=0;
        for(auto &i:sum1){
            int x=m-i-1;
            auto it=upper_bound(sum2.begin(),sum2.end(),x);
            --it;
            ans=max(ans,i+*it);
        }
        cout<


你可能感兴趣的:(E. Maximum Subsequence (meet-in-the-middle))