/* -*- 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; const long long LINF = 1LL << 62; /* 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); sort(as, as + n); int bits0 = 0, m = 0; ll sum0 = 0; for (int i = 0; i < n; i++) { if (as[i] >= 0) { bits0 |= (1 << i); sum0 += as[i]; } else m++; } 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; used.insert(bits1); if (q.size() < k - c) q.insert({sum1, bits1}); else if (q.begin()->first < sum1) { q.erase(q.begin()); q.insert({sum1, bits1}); } } } printf("%lld\n", sumk); return 0; }