#include <bits/stdc++.h> using namespace std; typedef long long ll; #define lit __builtin_popcount priority_queue <pair <ll, ll> > Q[2]; ll n, m, x, bits, candidates[10000000]; int main(){ cin >> n >> m; /*/ pre-processing /*/ Q[0].push({0, 0}); for (ll i = 0; i < 62; i ++) if ((1LL << i) < m) bits = i; bits += 2; /********************/ for (int o = 0; o < n; o ++){ cin >> x; ll best = LONG_MIN; while (!Q[o & 1].empty()){ ll num = -Q[o & 1].top().first; ll val = Q[o & 1].top().second; ll ind = 0; Q[o & 1].pop(); if (val <= best or num > m) continue; best = max(val, best); candidates[ind ++] = num; if (x < 0LL){ ll last_bits = lit(num); bool ok = true; for (ll i = 0; i < bits and ok; i ++){ if ((1LL << i) & num){ num -= (1LL << i); } else{ ll cand = (num | (1LL << i)); if (cand > m){ ok = false; } else if (lit(cand) < last_bits){ last_bits = lit(cand); candidates[ind ++] = cand; } } } } else{ for (ll i = 0; i < bits and num <= m; i ++) if (((1 << i) & num) == 0LL){ num |= (1 << i); if (num <= m) candidates[ind ++] = num; } } for (ll i = 0; i < ind; i ++) Q[o & 1 ^ 1].push({ -candidates[i] - 1, val + x * lit(candidates[i]) }); } } /* result */ ll best = LONG_MIN; while (!Q[n & 1].empty()){ best = max(best, Q[n & 1].top().second); Q[n & 1].pop(); } cout << best << "\n"; /*********/ return 0; }
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 84 85 86 87 | #include <bits/stdc++.h> using namespace std; typedef long long ll; #define lit __builtin_popcount priority_queue <pair <ll, ll> > Q[2]; ll n, m, x, bits, candidates[10000000]; int main(){ cin >> n >> m; /*/ pre-processing /*/ Q[0].push({0, 0}); for (ll i = 0; i < 62; i ++) if ((1LL << i) < m) bits = i; bits += 2; /********************/ for (int o = 0; o < n; o ++){ cin >> x; ll best = LONG_MIN; while (!Q[o & 1].empty()){ ll num = -Q[o & 1].top().first; ll val = Q[o & 1].top().second; ll ind = 0; Q[o & 1].pop(); if (val <= best or num > m) continue; best = max(val, best); candidates[ind ++] = num; if (x < 0LL){ ll last_bits = lit(num); bool ok = true; for (ll i = 0; i < bits and ok; i ++){ if ((1LL << i) & num){ num -= (1LL << i); } else{ ll cand = (num | (1LL << i)); if (cand > m){ ok = false; } else if (lit(cand) < last_bits){ last_bits = lit(cand); candidates[ind ++] = cand; } } } } else{ for (ll i = 0; i < bits and num <= m; i ++) if (((1 << i) & num) == 0LL){ num |= (1 << i); if (num <= m) candidates[ind ++] = num; } } for (ll i = 0; i < ind; i ++) Q[o & 1 ^ 1].push({ -candidates[i] - 1, val + x * lit(candidates[i]) }); } } /* result */ ll best = LONG_MIN; while (!Q[n & 1].empty()){ best = max(best, Q[n & 1].top().second); Q[n & 1].pop(); } cout << best << "\n"; /*********/ return 0; } |