Codeforces div2 edu E - Maximum Subsequence

题意:给定一个大小为n的数组,要求你从中选出一些数使得这些数的累和%m为最大值

n<=35; 35! = 14530444

我居然还傻傻的dp,这一题虽然是求最大值,但是并不存在局部最优解,用dp虽然过的了样例但是本质上确是错的离谱

正确的做法应该是折半搜索,这一点如果不能在看到n<=35时看出,简直就像看到数据大小超过int却不用longlong一样,而且这还是道div2e,蒟蒻没跑了

以n/2为分界线,分别dfs出左边与右边的所有状态并以辅助数组left,right,加以保存,然后分类讨论,枚举left,二分right时有两种情况

1. left+right<m 这时取right<m-left的最大值

2. m<=left+right<m*2 这时取right<m*2-left的最大值

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<algorithm>
#include<string>
#include<bitset>
#include<cmath>
#include<array>
#include<atomic>
#include<sstream>
#include<stack>
#include<iomanip>
//#include<bits/stdc++.h>

#define int ll
#define pb push_back
#define endl '\n'
#define x first
#define y second
#define Endl endl
#define pre(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,b,a) for(int i=b;i>=a;i--)
#define si(x) scanf("%d", &x);
#define sl(x) scanf("%lld", &x);
#define ss(x) scanf("%s", x);
#define YES {puts("YES");return;}
#define NO {puts("NO"); return;}
#define all(x) x.begin(),x.end()

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef pair<int, PII> PIII;
typedef pair<char, int> PCI;
typedef pair<int, char> PIC;
typedef pair<double, double> PDD;
typedef pair<ll, ll> PLL;
const int N = 200010, M = 2 * N, B = N, MOD = 1000000007;
const int INF = 0x3f3f3f3f;
const ll LLINF = 0x3f3f3f3f3f3f3f3f;

int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };
int n, m, k;
int a[N];
vector<int> l, r;

ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lowbit(ll x) { return x & -x; }
ll qmi(ll a, ll b, ll mod) {
    ll res = 1;
    while (b) {
        if (b & 1) res = res * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return res;
}

inline void init() {}

void dfs(int type, int u, int sum)
{
    if (!type && u == n / 2 + 1)
    {
        l.push_back(sum % m);
        return;
    }
    if (type && u == n + 1)
    {
        r.push_back(sum % m);
        return;
    }
    dfs(type, u + 1, sum % m);
    dfs(type, u + 1, (sum + a[u])%m);
    return;
}

void slove()
{
    cin >> n >> m;
    pre(i, 1, n)cin >> a[i];
    dfs(0, 1, 0); dfs(1, n / 2 + 1, 0);

    sort(all(r));
    int ans = 0,idx;
    for (int v : l)
    {
        idx = lower_bound(all(r), m - v) - r.begin();
        if (idx) ans = max((v + r[idx-1]) % m, ans);
        idx = lower_bound(all(r), m * 2 - v) - r.begin();
        if (idx) ans = max((v + r[idx-1]) % m, ans);
    }

    cout << ans << endl;
}

signed main()
{
    int _;
    //si(_);
    _ = 1;
    init();
    while (_--)
    {
        slove();
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值