CF888E:Maximum Subsequence(中途相遇)

本文介绍了一种通过折半搜索和二分法求解给定数列中若干个数的和取模最大值的问题,提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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}.

题意:给一个数列和m,在数列任选若干个数的和取模m最大。

思路:2的35次方会超时,考虑折半搜索,前后分别枚举,最后二分取最大值即可。

# include <bits/stdc++.h>
# define pb push_back
# define mp make_pair
using namespace std;
typedef long long LL;
LL a[40], n, m;
set<LL>s, t;
void dfs(int cur, LL sum)
{
    if(cur == n/2+1)
    {

        sum = sum%m;
        s.insert(sum);
        return;
    }
    dfs(cur+1, sum);
    dfs(cur+1, sum+a[cur]);
}
void dfs2(int cur, LL sum)
{
    if(cur == n+1)
    {
        sum = sum%m;
        t.insert(sum);
        return;
    }
    dfs2(cur+1, sum);
    dfs2(cur+1,sum+a[cur]);
}
int main()
{
    scanf("%lld%lld",&n,&m);
    for(int i=1; i<=n; ++i) scanf("%lld",&a[i]);
    dfs(1, 0);
    dfs2(n/2+1, 0);
    LL ans = 0;
    for(auto it=s.begin(); it!=s.end(); ++it)
    {
        LL tmp = *it;
        auto pos = t.lower_bound(m-tmp);
        if(pos != t.begin())
        {
            --pos;
            if(*pos + tmp <= m)
            ans = max(ans, *pos + tmp);
        }
    }
    printf("%lld\n",ans);
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值