888E - Maximum Subsequence - CodeForces Solution


bitmasks divide and conquer meet-in-the-middle *1800

Please click on ads to support us..

C++ Code:

// https://codeforces.com/contest/888/problem/E

#include <cstdio>
#include <algorithm>
#include <functional>
#include <vector>
#include <cstring>
using namespace std;
typedef long long ll;
typedef pair<int,int> pi;

int n, m;   // n <= 35
int a[40];  
vector<int> ml, mr;
int ans;

void generate(int l, int r, vector<int> &res) {
    for (int bm = 0; bm < (1 << (r-l+1)); bm++) {
        int sum = 0;
        for (int i = 0; i < r-l+1; i++) {
            if (bm & (1 << i)) 
                sum = (sum + a[l+i]) % m;
        }
        res.push_back(sum);
    }
    sort(res.begin(), res.end());
    res.resize(unique(res.begin(), res.end()) - res.begin());
}

int main() {
    scanf("%d %d", &n, &m);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    generate(0, n/2, ml);
    generate(n/2+1, n-1, mr);
    ans = max(ml.back(), mr.back());
    for (int x: ml) {
        auto it = lower_bound(mr.begin(), mr.end(), m-1-x);
        if (it != mr.end() && *it == m-1-x) {
            printf("%d", m-1); return 0;
        }
        if (it == mr.end() || *it > m-1-x && it != mr.begin()) {
            it--;
            ans = max(ans, x + *it);
        }
        // 对于x+y > m,这个一定不如单选x(或y)好,因为(x+y) % m < x
        // ans = max(ans, (x + mr.back()) % m);
    }
    printf("%d\n", ans);

    return 0;
}


Comments

Submit
0 Comments
More Questions

169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake
1584B - Coloring Rectangles
1562B - Scenes From a Memory
1521A - Nastia and Nearly Good Numbers
208. Implement Trie
1605B - Reverse Sort
1607C - Minimum Extraction
1604B - XOR Specia-LIS-t