/* -*- coding: utf-8 -*- * * 2370.cc: No.2370 He ate many cakes - yukicoder */ #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 30; const int NBITS = 1 << MAX_N; /* typedef */ using ll = long long; using pli = pair; using spli = set; using usi = unordered_set; /* global variables */ int as[MAX_N]; /* subroutines */ /* main */ int main() { int n, k; scanf("%d%d", &n, &k); for (int i = 0; i < n; i++) scanf("%d", as + i); int nbits = 1 << n, bits0 = 0; ll sum0 = 0; for (int i = 0; i < n; i++) if (as[i] >= 0) { bits0 |= (1 << i); sum0 += as[i]; } spli q; q.insert({sum0, bits0}); usi used; used.insert(bits0); int c = 0; ll sumk = 0; while (c < k && ! q.empty()) { auto sit = q.end(); sit--; auto [s, bits] = *sit; q.erase(sit); if (++c >= k) { sumk = s; break; } for (int i = 0, bi = 1; i < n; i++, bi <<= 1) if (used.find(bits ^ bi) == used.end()) { ll sum1 = s + ((bits & bi) ? -as[i] : as[i]); int bits1 = bits ^ bi; q.insert({sum1, bits1}); used.insert(bits1); } while (q.size() > k - c) q.erase(q.begin()); } printf("%lld\n", sumk); return 0; }