codeforces 888 E. Maximum Subsequence(好题)

最大子序列和问题
本文介绍了一个关于寻找整数数组中特定子序列的问题,该子序列使得其元素和除以给定整数后的余数最大化。文章提供了一个解决此问题的C++实现代码示例,该算法采用两阶段选择子序列的方法并利用排序和二分查找来提高效率。
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 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;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值