1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

#define ST first
#define ND second
#define PB push_back

int main() {
    ios_base::sync_with_stdio(0);
    ll n, m;
    cin >> n >> m;
    vector<pll> v, u;
    v.PB({0, 0});
    int max_usize=0;
    for(ll i=0; i < n; i++) {
        u.clear();
        ll a;
        cin >> a;
        for(pll x : v) {
            ll b = x.ST;
            ll tot = __builtin_popcountll(b);
            ll k = 0;
            vector<pll> w;
            if(a >= 0) {
                ll ptot=tot-1;
                while(b <= m) {
                    if(ptot < tot) {
                        w.PB({b+1, x.ND+tot*a});
                        ptot = tot;
                    }
                    while(true) {
                        if(((1LL<<k)&b) == 0) {
                            b|=(1LL<<k);
                            tot++;
                            break;
                        }
                        k++;
                    }
                }
            } else {
                ll ptot = tot+1;
                while(b <= m) {
                    if(ptot > tot) {
                        w.PB({b+1, x.ND+tot*a});
                        ptot = tot;
                    }
                    while(true) {
                        if(((1LL<<k)&b) != 0) {
                            b^=(1LL<<k);
                            tot--;
                        } else {
                            b^=(1LL<<k);
                            tot++;
                            break;
                        }
                        k++;
                    }
                }
            }
            for(int j=w.size()-1; j >= 0; j--) {
                if(u.size() == 0 || u.back().ST > w[j].ST) {
                    while(u.size() > 0 && u.back().ND <= w[j].ND) {
                        u.pop_back();
                    }
                    u.PB(w[j]);
                }
            }
        }
        // for(pll x : u) {
        //     cerr << x.ST << "," << -x.ND << " ";
        // }
        // cerr << "\n";
        max_usize = max(max_usize, (int)u.size());
        // cerr << "size: " << v.size() << " " << u.size() << endl;
        swap(v, u);
    }
    // cerr << max_usize << "\n";
    cout << v[0].ND << "\n";
}