solution
stringlengths
11
983k
difficulty
int64
0
21
language
stringclasses
2 values
#include <bits/stdc++.h> using namespace std; const long long MOD = (long long)1e9 + 7; const double PI = acos(-1.0); void __print(long long x) { cerr << x; } void __print(int32_t x) { cerr << x; } void __print(double x) { cerr << x; } void __print(long double x) { cerr << x; } void __print(char x) { cerr << '\'' << x << '\''; } void __print(const char *x) { cerr << '\"' << x << '\"'; } void __print(const string &x) { cerr << '\"' << x << '\"'; } template <typename T, typename V> void __print(const pair<T, V> &x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; } template <typename T> void __print(const T &x) { long long f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; } void _print() { cerr << "]\n"; } template <typename T, typename... V> void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); } int32_t main() { long long n, k; cin >> n >> k; multiset<long long> a, b, c; for (long long i = 0; i < n; i++) { long long t, p, q; cin >> t >> p >> q; if (p && q) { c.insert(t); } else if (p) { a.insert(t); } else if (q) { b.insert(t); } } if ((long long)a.size() + (long long)c.size() < k || (long long)b.size() + (long long)c.size() < k) { cout << -1 << '\n'; return 0; } long long cnt1 = a.size(), cnt2 = b.size(); long long ans = 0; for (auto x : a) ans += x; for (auto x : b) ans += x; multiset<long long> aa, bb; while (cnt1 < k || cnt2 < k) { long long cur = *c.begin(); aa.insert(cur); bb.insert(cur); ans += cur; cnt1++; cnt2++; c.erase(c.begin()); } while (cnt1 > k && a.size()) { ans -= *a.rbegin(); a.erase(--a.end()); cnt1--; } while (cnt2 > k && b.size()) { ans -= *b.rbegin(); b.erase(--b.end()); cnt2--; } while (c.size() && (a.size() || b.size())) { if (a.size() && b.size()) { if (*c.begin() < *a.rbegin() + *b.rbegin()) { ans -= *a.rbegin(); ans -= *b.rbegin(); ans += *c.begin(); a.erase(--a.end()); b.erase(--b.end()); c.erase(c.begin()); } else { break; } } else if (a.size()) { if (*c.begin() < *a.rbegin()) { ans -= *a.rbegin(); ans += *c.begin(); a.erase(--a.end()); c.erase(c.begin()); } else { break; } } else { if (*c.begin() < *b.rbegin()) { ans -= *b.rbegin(); ans += *c.begin(); b.erase(--b.end()); c.erase(c.begin()); } else { break; } } } cout << ans << '\n'; return 0; }
11
CPP
# @author import sys class E1ReadingBooksEasyVersion: def solve(self, tc=0): n, k = [int(_) for _ in input().split()] books = [] for i in range(n): books.append([int(_) for _ in input().split()]) a = [] b = [] both = [] for i in range(n): book = books[i] if book[1] and book[2]: both.append(book[0]) elif book[1]: a.append(book[0]) elif book[2]: b.append(book[0]) a.sort() b.sort() both.sort() # print(a) # print(b) # print(both) prea = [0] * (len(a) + 1) for i in range(1, len(a) + 1): prea[i] = prea[i - 1] + a[i - 1] preb = [0] * (len(b) + 1) for i in range(1, len(b) + 1): preb[i] = preb[i - 1] + b[i - 1] preboth = [0] * (len(both) + 1) for i in range(1, len(both) + 1): preboth[i] = preboth[i - 1] + both[i - 1] ans = float('inf') for i in range(len(both) + 1): if i > k: break if len(a) >= k - i and len(b) >= k - i: ans = min(ans, preboth[i] + prea[k - i] + preb[k - i]) print(ans if ans != float('inf') else -1) # na, nb, nboth # na + nboth = k # nb + nboth = k solver = E1ReadingBooksEasyVersion() input = sys.stdin.readline solver.solve()
11
PYTHON3
n, k = map(int, input().split()) alice = [] bob = [] both = [] for i in range(n): t, a ,b = map(int, input().split()) if a==b==1: both.append(t) elif a==1: alice.append(t) elif b==1: bob.append(t) alen = len(alice) blen = len(bob) mini = min(alen, blen) alice.sort() bob.sort() result = [] bot_taken = 0 ab = [] for i in range(mini): ab .append(alice[i]+bob[i]) last_list = ab+both last_list.sort() if len(last_list)<k: print(-1) else: print(sum(last_list[:k]))
11
PYTHON3
from sys import stdin, stdout def main(): n, k = map(int, stdin.readline().split()) alice = [] bob = [] both = [] ans = 0 for i in range(n): t, a, b = map(int, stdin.readline().split()) ans += t if a == 1 and b == 1: both.append(t) elif a == 1: alice.append(t) elif b == 1: bob.append(t) else: pass alice.sort() bob.sort() both.sort() #print(alice, bob, both) for i in range(1, len(alice)): alice[i] += alice[i - 1] for i in range(1, len(bob)): bob[i] += bob[i - 1] for i in range(1, len(both)): both[i] += both[i - 1] la, lbb, lbo = len(alice), len(bob), len(both) if la + lbo < k or lbb + lbo < k: ans = -1 else: for i in range(lbo): rest = k - i - 1 if rest > 0: if la >= rest and lbb >= rest: ans = min(ans, both[i] + alice[rest - 1] + bob[rest - 1]) else: ans = min(ans, both[i]) if la >= k and lbb >= k: ans = min(ans, alice[k - 1] + bob[k - 1]) stdout.write(str(ans)) stdout.write('\n') return if __name__ == '__main__': main()
11
PYTHON3
#include <bits/stdc++.h> using namespace std; static bool comp(long long int a, long long int b) { return (a > b); } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int n, k; cin >> n >> k; vector<long long int> A, B, BB; for (long long int i = 0; i < n; i++) { long long int t, a, b; cin >> t >> a >> b; if (a == 0 and b == 0) continue; if (a == 1 and b == 1) { BB.push_back(t); } else if (a == 1) { A.push_back(t); } else if (b == 1) { B.push_back(t); } } sort(A.begin(), A.end()); sort(B.begin(), B.end()); for (long long int i = 0; i < min(A.size(), B.size()); i++) BB.push_back(A[i] + B[i]); sort(BB.begin(), BB.end()); if (BB.size() < k) cout << "-1\n"; else { long long int s = 0; for (long long int i = 0; i < k; i++) s += BB[i]; cout << s << '\n'; } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; const int mod = 1e9 + 7; long long a[N], a1 = 0, b[N], b1 = 0, c[N], c1 = 0, d, dis; char o; pair<int, int> p; bool mark = true; int main() { ios::sync_with_stdio(false); cin.tie(0); long long t, n, m, mx, k, ans = 0, sum = 0, x, y, l, r; string s; cin >> n >> k; for (int i = 0; i < n; i++) { cin >> l >> m >> t; if (m == 1 && t == 1) { c[c1++] = l; } if (m == 1 && t == 0) { a[a1++] = l; } if (m == 0 && t == 1) { b[b1++] = l; } } sort(a, a + a1); sort(b, b + b1); sort(c, c + c1); long long a2 = 0, b2 = 0, c2 = 0; m = min(a1, b1); m = k - m; if (c1 < m) cout << -1 << endl; else { c2 = max(c2, m); for (int i = 0; i < m; i++) { ans += c[i]; } m = min(a1, b1); if (m > k) m = k; for (int i = 0; i < m; i++) { if (c2 < c1 && a[a2] + b[b2] >= c[c2]) ans += c[c2++]; else { ans += a[a2++]; ans += b[b2++]; } } cout << ans; } }
11
CPP
n,k=map(int,input().split()) t11=[] t01=[] t10=[] for j in range(n): ti,ai,bi=map(int,input().split()) if(ai==0 and bi==0): continue elif (ai==1 and bi==1): t11.append(ti) elif (ai==0 and bi==1): t01.append(ti) else: t10.append(ti) lt11=len(t11) lt10=len(t10) lt01=len(t01) if(lt11+min(lt10,lt01)>=k): #t11=sorted(t11) t01=sorted(t01) t10=sorted(t10) t1=t0=tot=0 for i in range(min(lt10,lt01)): t11.append(t10[i]+t01[i]) ''' while k>0: k-=1 if (t1<lt11): tot=tot+t11[t1] t1+=1 elif (t0<lt01 and t0<lt10): tot+=t10[t0]+t01[t0] t0+=1 else: print("-1"); break print(tot) ''' print(sum(sorted(t11)[:k])) else: print("-1")
11
PYTHON3
n,k = map(int, input().split()) oo = list() oa = list() ob = list() for i in range(n): t,a,b = map(int, input().split()) if a == 1 and b == 1: oo.append(t) elif a == 0 and b == 1: ob.append(t) elif a == 1 and b == 0: oa.append(t) oo = sorted(oo) oa = sorted(oa) ob = sorted(ob) oo_p = 0 oa_p = 0 ob_p = 0 ca = 0 cb = 0 ans = 0 MAX = 23942034809238409823048 if max(0, max(k-len(oa), k-len(ob))) > len(oo): print("-1") exit(0) def get_first_elem_from_list(l, pos): if pos < len(l): return l[pos] else: return MAX def remove_first_elem_from_list(l, pos): if len(l)>pos: pos += 1 return pos while ca < k or cb < k: oo_f = get_first_elem_from_list(oo, oo_p) oa_f = get_first_elem_from_list(oa, oa_p) ob_f = get_first_elem_from_list(ob, ob_p) if ca < k and cb < k: if oo_f <= oa_f + ob_f: if oo_f == MAX: print("-1") exit(0) else: ca += 1 cb += 1 ans+=oo_f oo_p = remove_first_elem_from_list(oo, oo_p) elif oa_f + ob_f < oo_f: if oa_f + ob_f >= MAX: print("-1") exit(0) else: ca += 1 cb += 1 ans+=oa_f+ob_f oa_p = remove_first_elem_from_list(oa, oa_p) ob_p = remove_first_elem_from_list(ob, ob_p) elif ca < k: if oo_f <= oa_f: if oo_f == MAX: print("-1") exit(0) else: ca += 1 ans+=oo_f oo_p = remove_first_elem_from_list(oo, oo_p) elif oa_f < oo_f: if oa_f >= MAX: print("-1") exit(0) else: ca += 1 ans+=oa_f oa_p = remove_first_elem_from_list(oa, oa_p) else: if oo_f <= ob_f: if oo_f == MAX: print("-1") exit(0) else: cb += 1 ans+=oo_f oo_p = remove_first_elem_from_list(oo, oo_p) elif ob_f < oo_f: if ob_f >= MAX: print("-1") exit(0) else: cb += 1 ans+=ob_f ob_p = remove_first_elem_from_list(ob, ob_p) print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { int n, k, t, a, b, sum = 0, cnt = 0; vector<int> A, B, C; cin >> n >> k; for (int i = 1; i <= n; i++) { cin >> t >> a >> b; if (a != b) { if (a == 1) { A.push_back(t); } else { B.push_back(t); } } else { if (a == 1) { C.push_back(t); } } } sort(A.begin(), A.end()); sort(B.begin(), B.end()); sort(C.begin(), C.end()); if (A.size() + C.size() < k) { cout << -1; return 0; } else if (B.size() + C.size() < k) { cout << -1; return 0; } else { int i = 0, j = 0, l = 0; while (i < A.size() && j < B.size() && l < C.size() && cnt < k) { if (A[i] + B[j] < C[l]) { sum += A[i] + B[j]; i++; j++; cnt++; } else { sum += C[l]; l++; cnt++; } } if (cnt < k) { if (l == C.size()) { l = cnt; while (l < k) { sum += A[i]; i++; l++; } l = cnt; while (l < k) { sum += B[j]; j++; l++; } } else { i = cnt; while (i < k) { sum += C[l]; l++; i++; } } } } cout << sum; return 0; }
11
CPP
import io import os # Based on https://raw.githubusercontent.com/cheran-senthil/PyRival/master/pyrival/data_structures/SortedList.py # Modified to do range sum queries class SortedListWithSum: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._sum = sum(values) self._load = _load self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)] self._mins = [_list[0] for _list in _lists] self._list_lens = [len(_list) for _list in _lists] self._fen_tree = [] self._list_sums = [sum(_list) for _list in _lists] self._fen_tree_sum = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._fen_tree_sum[:] = self._list_sums _fen_tree_sum = self._fen_tree_sum for i in range(len(_fen_tree_sum)): if i | i + 1 < len(_fen_tree_sum): _fen_tree_sum[i | i + 1] += _fen_tree_sum[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_update_sum(self, index, value): """Update `fen_tree2[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree_sum while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_query_sum(self, end): """Return `sum(_fen_tree_sum[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree_sum x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens _list_sums = self._list_sums value = _lists[pos][idx] self._len -= 1 self._sum -= value self._fen_update(pos, -1) self._fen_update_sum(pos, -value) del _lists[pos][idx] _list_lens[pos] -= 1 _list_sums[pos] -= value if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _list_sums[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens _list_sums = self._list_sums self._len += 1 self._sum += value if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) self._fen_update_sum(pos, value) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _list_sums[pos] += value _mins[pos] = _list[0] if _load + _load < len(_list): back = _list[_load:] old_len = _list_lens[pos] old_sum = _list_sums[pos] new_len_front = _load new_len_back = old_len - new_len_front new_sum_back = sum(back) new_sum_front = old_sum - new_sum_back _lists.insert(pos + 1, back) _list_lens.insert(pos + 1, new_len_back) _list_sums.insert(pos + 1, new_sum_back) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = new_len_front _list_sums[pos] = new_sum_front del _list[_load:] # assert len(_lists[pos]) == _list_lens[pos] # assert len(_lists[pos + 1]) == _list_lens[pos + 1] # assert sum(_lists[pos]) == _list_sums[pos] # assert sum(_lists[pos + 1]) == _list_sums[pos + 1] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) _list_sums.append(value) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError("{0!r} not in list".format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return "SortedList({0})".format(list(self)) def query(self, i, j): if i == j: return 0 pos1, idx1 = self._fen_findkth(self._len + i if i < 0 else i) pos2, idx2 = self._fen_findkth(self._len + j if j < 0 else j) return ( sum(self._lists[pos1][idx1:]) + (self._fen_query_sum(pos2) - self._fen_query_sum(pos1 + 1)) + sum(self._lists[pos2][:idx2]) ) def sum(self): return self._sum def solve(N, M, K, books): A = [] B = [] common = [] padding = SortedListWithSum() for i, (t, a, b) in enumerate(books): if a and b: common.append(t) elif a: A.append(t) elif b: B.append(t) else: padding.add(t) A.sort() B.sort() common.sort() prefA = [0] for t in A: prefA.append(prefA[-1] + t) prefB = [0] for t in B: prefB.append(prefB[-1] + t) prefC = [0] for t in common: prefC.append(prefC[-1] + t) # Check allowable number of common books cMin = max(0, K - len(A), K - len(B), 2 * K - M) cMax = min(K, len(common)) if cMin > cMax: return -1 # Want to contain every book in: common[:c], B[: K - c], A[: K - c], padding # starting with c = cMin for i in range(cMin, len(common)): padding.add(common[i]) for i in range(K - cMin, len(A)): padding.add(A[i]) for i in range(K - cMin, len(B)): padding.add(B[i]) best = (float("inf"),) for c in range(cMin, cMax + 1): # Take c common books to satisfy both # Need K - c more from A and B each assert 0 <= c <= len(common) assert 0 <= K - c <= len(A) assert 0 <= K - c <= len(B) # Pad this up to make M books exactly pad = M - c - (K - c) * 2 assert 0 <= pad <= N cost = prefC[c] + prefB[K - c] + prefA[K - c] + padding.query(0, min(pad, len(padding))) best = min(best, (cost, c)) # On next iteration, A[K-c-1] and B[K-c-1] won't be needed # Move them to padding if 0 <= K - c - 1 < len(A): x = A[K - c - 1] padding.add(x) if 0 <= K - c - 1 < len(B): x = B[K - c - 1] padding.add(x) # On next iteration, common[c] will be needed if c < len(common): x = common[c] padding.remove(x) assert best[0] != float("inf") # Reconstruct needC = best[1] needA = K - needC needB = K - needC needPad = M - needC - needB - needA check = 0 ans = [] for i, (t, a, b) in sorted(enumerate(books), key=lambda ix: ix[1][0]): if a and b: if needC: needC -= 1 ans.append(str(i + 1)) check += t continue if a: if needA: needA -= 1 ans.append(str(i + 1)) check += t continue if b: if needB: needB -= 1 ans.append(str(i + 1)) check += t continue if needPad: needPad -= 1 ans.append(str(i + 1)) check += t assert len(ans) == M assert check == best[0] return str(best[0]) + "\n" + " ".join(x for x in ans) if False: import random random.seed(0) N = 2 * 10 ** 2 for i in range(1000): books = [ [random.randint(1, 20), random.randint(0, 1), random.randint(0, 1)] for i in range(N) ] M = min(N, random.randint(1, 100)) K = min(M, random.randint(1, 100)) # print(N, M, K, books) solve(N, M, K, books) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, M, K = [int(x) for x in input().split()] books = [[int(x) for x in input().split()] for i in range(N)] ans = solve(N, M, K, books) print(ans)
11
PYTHON3
n,k = [int(x) for x in input().split()] at = [] bt = [] ct = [] for i in range(n): ti,ai,bi = [int(x) for x in input().split()] if ai == 1 and bi == 1: ct.append(ti) elif ai == 1: at.append(ti) elif bi == 1: bt.append(ti) else: continue if len(ct)+len(at)<k or len(ct)+len(bt)<k: print(-1) else: ci = 0 ai = 0 # bi = 0 al = k # bl = k ans = 0 ct.sort() at.sort() bt.sort() # for i in range(len(ct)): i=0 # print(at,bt,ct) while(i<len(ct) and al>0 and ai<min(len(at),len(bt))): if ct[i]<at[ai]+bt[ai]: ans+=ct[i] # al-=1 i+=1 else: ans+=at[ai]+bt[ai] # al-=1 ai+=1 al-=1 # print(i,ai,ans) if (i==len(ct) and al!=0): bl = al ans+=sum(at[ai:ai+al])+sum(bt[ai:ai+al]) elif(ai == min(len(at),len(bt)) and al>0): ans+=sum(ct[i:i+al]) print(ans) # if len(ct)>=k: # ct.sort() # print(sum(ct[:k])) # else: # aleft = k - len(ct) # bleft = k - len(ct) # ans = sum(ct) # at.sort() # bt.sort() # ans+=sum(at[:aleft])+sum(bt[:bleft]) # print(ans)
11
PYTHON3
# T = int(input().strip()) # for t in range(T): n, k = list(map(int, input().split())) al = [] bl = [] all = [] for bb in range(n): t, a, b = list(map(int, input().split())) if a == 1: if b == 1: all.append(t) else: al.append(t) elif b == 1: bl.append(t) ml = min(len(al), len(bl)) if len(all) + ml <k: print(-1) else: al = sorted(al) bl = sorted(bl) for j in range(ml): all.append(al[j]+bl[j]) all = sorted(all) print(sum(all[:k]))
11
PYTHON3
from collections import Counter, defaultdict BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def to_base(s, b): res = "" while s: res+=BS[s%b] s//= b return res[::-1] or "0" alpha = "abcdefghijklmnopqrstuvwxyz" from math import floor, ceil,pi import sys primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919 ] import timeit def primef(n, plst = []): if n==1: return plst else: for m in primes: if n%m==0: return primef(n//m, plst+[m]) return primef(1, plst+[n]) def lmii(): return list(map(int, input().split())) def ii(): return int(input()) def countOverlapping(string,sub): count = start = 0 while True: start = string.find(sub, start)+1 if start > 0: count += 1 else: return count n,k = lmii() gotA = [] gotB = [] got = [] nums = [list(map(int, sys.stdin.readline().split())) for i in range(n)] nums.sort() for i in range(n): a,b,c = nums[i] #print(a,b,c, gotA, gotB) if b+c==2: got.append(a) elif b+c !=0: if b==0: if gotB: aa,bb,cc = gotB.pop(0) got.append(aa+a) else: gotA.append((a,b,c)) else: if gotA: aa,bb,cc = gotA.pop(0) got.append(aa+a) else: gotB.append((a,b,c)) got.sort() if len(got) < k: print(-1) else: print(sum(got[:k]))
11
PYTHON3
n,k = map(int, input().split()) a = [] b = [] comman = [] a_ = [] b_ = [] for _ in range(n): t,ai,bi = map(int, input().split()) a_.append(ai) b_.append(bi) if ai == 1 and bi == 1: comman.append(t) elif ai == 1: a.append(t) elif bi == 1: b.append(t) a.sort() b.sort() #comman.sort() if a_.count(1) < k or b_.count(1) < k: print(-1) else: s = 0 m = min(len(a),len(b)) for i in range(m): comman.append(a[i]+b[i]) comman.sort() print(sum(comman[:k]))
11
PYTHON3
n, k = map(int, input().split()) a = [] for i in range(n): x,y,z = map(int, input().split()) a.append([x,y,z]) alice_count = 0 bob_count = 0 alice = [] bob = [] combine = [] for i in range(n): if a[i][1] == 1 and a[i][2] == 1: combine.append(a[i][0]) alice_count += 1 bob_count += 1 elif a[i][1] == 1: alice.append(a[i][0]) alice_count += 1 elif a[i][2] == 1: bob.append(a[i][0]) bob_count += 1 if alice_count < k or bob_count < k: print('-1') else: alice_len = len(alice) bob_len = len(bob) combine_len = len(combine) alice.sort() bob.sort() combine.sort() ans = 0 i1 = 0 i2 = 0 while(i1 + i2 < k): if i1 < bob_len and i1 < alice_len and i2 < combine_len: if bob[i1] + alice[i1] > combine[i2]: ans += combine[i2] i2 += 1 else: ans += bob[i1] + alice[i1] i1 += 1 elif i1 >= bob_len or i1 >= alice_len: ans += combine[i2] i2 += 1 elif i2 >= combine_len: ans += bob[i1] + alice[i1] i1 += 1 print(ans)
11
PYTHON3
n, k = map(int, input().split()) common, alice, bob = [0], [0], [0] for i in range(n): t, a, b = map(int, input().split()) if (a+b) == 2: common.append(t) elif a == 1: alice.append(t) elif b == 1: bob.append(t) common.sort() alice.sort() bob.sort() for i in range(1, len(common)): common[i] += common[i-1] for i in range(1, len(alice)): alice[i] += alice[i-1] for i in range(1, len(bob)): bob[i] += bob[i-1] ans = 10**20 for i in range(len(common)): t = common[i] r = k-i if r >= 0 and r < len(alice) and r < len(bob): t += alice[r]+bob[r] ans = min(ans, t) if ans < 10**20: print(ans) else: print(-1)
11
PYTHON3
#!/usr/bin/env python3 import sys import heapq input=sys.stdin.readline n,k=map(int,input().split()) arr=[list(map(int,input().split())) for _ in range(n)] cnt1=0 cnt2=0 for t,a,b in arr: if a==1: cnt1+=1 if b==1: cnt2+=1 if cnt1<k or cnt2<k: print(-1) exit() arr=sorted(arr,key=lambda x:x[0]) arr=sorted(arr,reverse=True,key=lambda x:x[1]) ans=0 cnt=0 for i in range(k): ans+=arr[i][0] if arr[i][2]==1: cnt+=1 if cnt==k: print(ans) exit() q1=[] q2=[] q3=[] for t,a,b in arr[:k]: if a==1 and b==0: heapq.heappush(q1,-t) for t,a,b in arr[k:]: if a==1 and b==1: heapq.heappush(q2,t) if a==0 and b==1: heapq.heappush(q3,t) INF=10**18 while cnt<k: if len(q1)!=0: diff1=INF if len(q2)!=0: cost1=heapq.heappop(q1) heapq.heappush(q1,cost1) cost2=heapq.heappop(q2) heapq.heappush(q2,cost2) diff1=cost1+cost2 diff2=INF if len(q3)!=0: cost3=heapq.heappop(q3) heapq.heappush(q3,cost3) diff2=cost3 if diff1!=INF and diff2==INF: ans+=diff1 heapq.heappop(q1) heapq.heappop(q2) elif diff1==INF and diff2!=INF: ans+=diff2 heapq.heappop(q3) else: if diff1<=diff2: ans+=diff1 heapq.heappop(q1) heapq.heappop(q2) else: ans+=diff2 heapq.heappop(q3) else: diff1=INF if len(q2)!=0: cost2=heapq.heappop(q2) heapq.heappush(q2,cost2) diff1=cost2 diff2=INF if len(q3)!=0: cost3=heapq.heappop(q3) heapq.heappush(q3,cost3) diff2=cost3 if diff1!=INF and diff2==INF: ans+=diff1 heapq.heappop(q2) elif diff1==INF and diff2!=INF: ans+=diff2 heapq.heappop(q3) else: if diff1<=diff2: ans+=diff1 heapq.heappop(q2) else: ans+=diff2 heapq.heappop(q3) cnt+=1 print(ans)
11
PYTHON3
def p(x): return x[0] n, k = map(int, input().split()) a = [] for i in range(n): a.append(list(map(int, input().split()))) a.sort(key=p) # print() # print() # for i in a: # print(i) alice, bob, common = [], [], [] al, bo = 0, 0 flag = 1 for i in a: if(i[1] and not i[2] and al < k): alice.append(i[0]) al += 1 if(i[2] and (not i[1]) and bo < k): bob.append(i[0]) bo += 1 if(i[1] and i[2]): if(al<k or bo<k): common.append(i[0]) al += 1 bo += 1 if(al > k and alice): alice.pop() al -= 1 if(bo > k and bob): bob.pop() bo -= 1 else: if(alice and bob): if(alice[-1]+bob[-1] > i[0]): alice.pop() bob.pop() common.append(i[0]) else: break # print(alice, bob, common, al, bo) if(al >= k and bo >= k): print(sum(alice)+sum(bob)+sum(common)) else: print(-1)
11
PYTHON3
import itertools n, k = map(int,input().split()) both = [0] alice = [0] bob = [0] for _ in range(n): t, a, b = map(int,input().split()) if a and b: both.append(t) elif a: alice.append(t) elif b: bob.append(t) if len(alice)+len(both) < k or len(bob)+len(both) < k: print(-1) exit() both.sort() alice.sort() bob.sort() cs_both = list(itertools.accumulate(both)) cs_alice = list(itertools.accumulate(alice)) cs_bob = list(itertools.accumulate(bob)) """ print(cs_both) print(cs_alice) print(cs_bob) """ ans = float('inf') for i in range(k+1): try: tmp = cs_both[i] except IndexError: break if i == k: ans = min(ans, tmp) try: tmp += cs_alice[k-i] except IndexError: continue try: tmp += cs_bob[k-i] except IndexError: continue ans = min(ans, tmp) if ans == float('inf'): print(-1) else: print(ans)
11
PYTHON3
from __future__ import division, print_function # import threading # threading.stack_size(2**27) # import sys # sys.setrecursionlimit(10**7) # sys.stdin = open('inpy.txt', 'r') # sys.stdout = open('outpy.txt', 'w') from sys import stdin, stdout import bisect #c++ upperbound import math import heapq # i_m=9223372036854775807 def inin(): return int(input()) def stin(): return input() def spin(): return map(int,stin().split()) def lin(): #takes array as input return list(map(int,stin().split())) def matrix(n): #matrix input return [list(map(int,input().split()))for i in range(n)] ################################################ def count2Dmatrix(i,list): return sum(c.count(i) for c in list) def modinv(n,p): return pow(n,p-2,p) def GCD(x, y): x=abs(x) y=abs(y) if(min(x,y)==0): return max(x,y) while(y): x, y = y, x % y return x def Divisors(n) : l = [] for i in range(1, int(math.sqrt(n) + 1)) : if (n % i == 0) : if (n // i == i) : l.append(i) else : l.append(i) l.append(n//i) return l prime=[] def SieveOfEratosthenes(n): global prime prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 f=[] for p in range(2, n): if prime[p]: f.append(p) return f q=[] def dfs(n,d,v,c): global q v[n]=1 x=d[n] q.append(n) j=c for i in x: if i not in v: f=dfs(i,d,v,c+1) j=max(j,f) # print(f) return j # d = {} """*******************************************************""" n, k = spin() alice, bob, both = [], [], [] for _ in range(n): t, a, b = spin() if a&b: both.append(t) elif a==1: alice.append(t) elif b==1: bob.append(t) alice = sorted(alice) bob = sorted(bob) for i in range(min(len(alice), len(bob))): both.append(alice[i] + bob[i]) if len(both)>=k: print(sum(sorted(both)[:k])) else: print(-1) # print(alice, bob) # sa = sum(alice[:k]);sb = sum(bob[:k]) # def intersection(lst1, lst2): # temp = set(lst2) # lst3 = [value for value in lst1 if value in temp] # return lst3 # common = sum(intersection(alice[:k], bob[:k])) # common2 = sum(intersection(alice, bob)[:k]) # # print(intersection(alice, bob)) # if alice==intersection(alice, bob) or bob==intersection(alice, bob): # print(sum(intersection(alice, bob))) # else: # print(sa+sb-common)
11
PYTHON3
from sys import stdin ip=stdin.readline n,k=map(int, ip().split()) alike=[]; blike=[]; both=[] for _ in range(n): t,a,b=map(int, ip().split()) if a and b: both.append(t) elif a: alike.append(t) elif b: blike.append(t) lb=k-len(both); aln=len(alike); bln=len(blike) if aln<lb or bln<lb: print('-1') else: alike.sort(); blike.sort() both += [alike[i] + blike[i] for i in range(min(aln,bln))] both.sort() print(sum(both[:k:]))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; using Int = int64_t; vector<Int> csum(vector<Int> v) { vector<Int> r; r = v; for (int i = 1; i < r.size(); ++i) r[i] += r[i - 1]; return r; } int main() { Int N, K; cin >> N >> K; vector<Int> v, u, cmn; while (N--) { Int a, b, c; cin >> c >> a >> b; if (a + b == 0) continue; ; if (a + b == 2) cmn.emplace_back(c); else if (a == 1) v.emplace_back(c); else u.emplace_back(c); } sort(v.begin(), v.end()); sort(u.begin(), u.end()); sort(cmn.begin(), cmn.end()); auto cv = csum(v); auto cu = csum(u); auto ccmn = csum(cmn); Int ans = 1LL << 60; if (v.size() >= K && u.size() >= K) { ans = cv[K - 1] + cu[K - 1]; } if (cmn.size() >= K) ans = min(ans, ccmn[K - 1]); for (int i = 0; i < cmn.size(); ++i) { if (K - i - 2 < 0) continue; if (v.size() > K - i - 2 && u.size() > K - 2 - i) { ans = min(ans, cv[K - i - 2] + cu[K - i - 2] + ccmn[i]); } } cout << (ans == 1LL << 60 ? -1 : ans) << endl; }
11
CPP
n,k=map(int,input().split()) z=[] x=[] y=[] for i in range(n): t,a,b=map(int,input().split()) if a&b:z.append(t) elif a:x.append(t) elif b:y.append(t) x.sort() y.sort() for i in range(min(len(x),len(y))):z.append(x[i]+y[i]) print(-1if len(z)<k else sum(sorted(z)[:k]))
11
PYTHON3
n, m = map(int, input().split()) first = [] second = [] common = [] array = [] for s in range(n): a, b, c = map(int, input().split()) array.append([a, b, c]) f, s, d = 0, 0, 0 for i in range(n): a = array[i][0] b = array[i][1] c = array[i][2] if (b == 1 and c == 1): common.append(a) d += 1 elif (b == 1 and c == 0): first.append(a) f += 1 elif (b == 0 and c == 1): second.append(a) s += 1 mini = min(f, s) first.sort() second.sort() for i in range(mini): common.append(first[i] + second[i]) common.sort() add = 0 if (m <= d + mini): for i in range(m): add += common[i] print(add) else: print(-1)
11
PYTHON3
from sys import stdin, stdout n, k = map(int, stdin.readline().split()) alice = [] bob = [] together = [] for _ in range(n): t, a, b = map(int, stdin.readline().split()) if a and b: together += t, elif a: alice += t, elif b: bob += t, sa, sb, st = len(alice), len(bob), len(together) if sa + st < k or sb + st < k: stdout.write('-1') exit() alice.sort(reverse=True) bob.sort(reverse=True) together.sort(reverse=True) time = 0 for _ in range(k): if sa and sb and st: if together[-1] < alice[-1] + bob[-1]: time += together[-1] together.pop() st -= 1 else: time += alice[-1] + bob[-1] alice.pop() bob.pop() sa -= 1 sb -= 1 elif st: time += together[-1] together.pop() st -= 1 else: time += alice[-1] + bob[-1] alice.pop() bob.pop() sa -= 1 sb -= 1 stdout.write(str(time))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; long long int solve() { long long int n, k; cin >> n >> k; vector<long long int> first, second, both; int av = 0, bv = 0; while (n--) { long long int t, a, b; cin >> t >> a >> b; if (a && b) both.push_back(t), av++, bv++; else if (a) first.push_back(t), av++; else if (b) second.push_back(t), bv++; } if (av < k || bv < k) return -1; sort(first.begin(), first.end()); sort(second.begin(), second.end()); sort(both.begin(), both.end()); av = k, bv = k; int ia = 0, is = 0, ib = 0, sf = first.size(), ss = second.size(), sb = both.size(); long long int ans = 0; while (av > 0 && bv > 0) { if (ib < sb and ((ia >= sf || is >= ss) || both[ib] < first[ia] + second[is])) { ans += both[ib++]; av--; bv--; } else { ans += first[ia++] + second[is++]; av--; bv--; } } return ans; } int main() { cout << solve(); }
11
CPP
from fractions import Fraction import bisect import os import io from collections import Counter import bisect from collections import defaultdict import math import random import heapq as hq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itertools import combinations from io import BytesIO, IOBase from itertools import accumulate from queue import Queue # sys.setrecursionlimit(200000) # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def tinput(): return input().split() def rinput(): return map(int, tinput()) def rlinput(): return list(rinput()) mod = int(1e9)+7 def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) # ---------------------------------------------------- # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') t = 1 # t = iinput() oo = [] zo = [] oz = [] for _ in range(t): n, k = rinput() for i in range(n): t, a, b = rinput() if a == 1 and b == 1: oo.append(t) elif a == 1: oz.append(t) elif b==1: zo.append(t) oo.sort() zo.sort() oz.sort() poo = list(accumulate(oo)) pzo = list(accumulate(zo)) poz = list(accumulate(oz)) noo = len(oo) nzo = len(zo) noz = len(oz) ans = float('inf') # print(oz,zo,oo) for i in range(noo+1): want = k - i if nzo >= want and noz >= want and want > 0 and i==0: # print(want) ans = min(ans, pzo[want - 1] + poz[want - 1]) if nzo >= want and noz >= want and i > 0 and want > 0: ans = min(ans, poo[i - 1] + pzo[want - 1] + poz[want - 1]) # print('Hello') if want == 0 and i==k: ans=min(ans,poo[i-1]) print(-1 if ans==float('inf') else ans)
11
PYTHON3
n,k=list(map(int,input().strip().split())) list1=[] list2=[] list12=[] list0=[] for _ in range(n): x,y,z=list(map(int,input().strip().split())) if y==1 and z==1: list12.append(x) elif y==1: list1.append(x) elif z==1: list2.append(x) list1.sort() list2.sort() loop=min(len(list1),len(list2)) for i in range(loop): list12.append(list1[i]+list2[i]) list12.sort() if len(list12)<k: print(-1) else: ans=0 for i in range(k): ans+=list12[i] print(ans)
11
PYTHON3
from sys import stdin input = stdin.buffer.readline n, k = map(int, input().split()) a, b, c = [], [], [] for i in range(n): t, x, y = map(int, input().split()) if x & y: c.append(t) elif x: a.append(t) elif y: b.append(t) a.sort(reverse=True) b.sort(reverse=True) c.sort(reverse=True) ans = 0 for i in range(k): if a and b and c: if c[-1] < a[-1] + b[-1]: ans += c.pop() else: ans += a.pop() + b.pop() elif c: ans += c.pop() elif a and b: ans += a.pop() + b.pop() else: exit(print(-1)) print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; struct edge { long long int t; long long int a; long long int b; }; vector<edge> grp1; vector<edge> grp2; vector<edge> grp3; bool cmp(edge A, edge B) { return A.t < B.t; } int main() { edge get; long long int n, k, i, j, temp, aa, bb, tt, cnt1, cnt2, len1, len2, len3, res, dd; cnt1 = 0; res = 0; cnt2 = 0; cin >> n >> dd; for (i = 0; i < n; i++) { cin >> tt >> aa >> bb; if (aa == 1) cnt1++; if (bb == 1) cnt2++; get.t = tt; get.a = aa; get.b = bb; if (aa == 1 && bb == 1) { grp3.push_back(get); } else if (aa == 1 && bb == 0) { grp1.push_back(get); } else if (aa == 0 && bb == 1) { grp2.push_back(get); } } if (cnt1 < dd || cnt2 < dd) cout << -1 << endl; else { sort(grp1.begin(), grp1.end(), cmp); sort(grp2.begin(), grp2.end(), cmp); sort(grp3.begin(), grp3.end(), cmp); len1 = grp1.size(); len2 = grp2.size(); len3 = grp3.size(); i = 0; j = 0; k = 0; cnt1 = 0; cnt2 = 0; while (1) { if (i < len1 && j < len2 && k < len3) { temp = grp3[k].t; aa = grp1[i].t; bb = grp2[j].t; if (temp <= (aa + bb)) { res += temp; k++; cnt1++; cnt2++; } else { res += (aa + bb); i++; j++; cnt1++; cnt2++; } if (cnt1 == dd && cnt2 == dd) break; } else if (i < len1 && j < len2) { aa = grp1[i].t; bb = grp2[j].t; res += (aa + bb); cnt1++; cnt2++; i++; j++; if (cnt1 == dd && cnt2 == dd) break; } else { temp = grp3[k].t; res += temp; cnt1++; cnt2++; k++; if (cnt1 == dd && cnt2 == dd) break; } } cout << res << endl; } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; #pragma GCC target("sse4.2") int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int n, k; cin >> n >> k; vector<long long int> v[4]; vector<long long int> pref[4]; for (long long int i = 0; i < (long long int)n; i++) { long long int t, a, b; cin >> t >> a >> b; v[2 * a + b].push_back(t); } for (long long int i = 0; i < (long long int)4; i++) { sort(v[i].begin(), v[i].end()); pref[i].push_back(0ll); for (long long int j = 0; j < (long long int)v[i].size(); j++) pref[i].push_back(pref[i].back() + v[i][j]); } long long int ans = INT_MAX; for (long long int i = 0; i < min(k + 1, (long long int)pref[3].size()); i++) { if (k - i < pref[1].size() && k - i < pref[2].size()) { ans = min(ans, pref[3][i] + pref[1][k - i] + pref[2][k - i]); } } if (ans == INT_MAX) cout << "-1\n"; else cout << ans << "\n"; return 0; }
11
CPP
from collections import Counter,defaultdict,deque #from heapq import * #from itertools import * #from operator import itemgetter #from itertools import count, islice #from functools import reduce #alph = 'abcdefghijklmnopqrstuvwxyz' #dirs = [[1,0],[0,1],[-1,0],[0,-1]] #from math import factorial as fact #a,b = [int(x) for x in input().split()] #sarr = [x for x in input().strip().split()] #import math #from math import * import sys input=sys.stdin.readline #sys.setrecursionlimit(2**30) #MOD = 10**9+7 def primes(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors def solve(): n,k = [int(x) for x in input().split()] onlya = [] onlyb = [] both = [] for i in range(n): t,a,b = [int(x) for x in input().split()] if a and b: both.append(t) elif b: onlyb.append(t) elif a: onlya.append(t) onlya = deque(sorted(onlya)) both = deque(sorted(both)) onlyb = deque(sorted(onlyb)) ans = 0 for i in range(k): if len(both) == 0 and (len(onlya)*len(onlyb)==0): print(-1) return if not (len(onlya)*len(onlyb)) or len(both) and both[0]<=onlya[0]+onlyb[0]: ans+= both.popleft() else: if len(onlya)*len(onlyb)==0: print(-1) return ans+=onlya.popleft() ans+=onlyb.popleft() print(ans) tt = 1#int(input()) for test in range(tt): solve() #
11
PYTHON3
from collections import deque import sys def inp(): return sys.stdin.readline().strip() for _ in range(1): n,k=map(int,inp().split()) l=[] a=[] b=[] for i in range(n): ti,ai,bi=map(int,inp().split()) if ai==0 and bi==0: continue elif ai==0: b.append(ti) elif bi==0: a.append(ti) else: l.append(ti) if len(a)+len(l)<k or len(b)+len(l)<k: print(-1) continue a.sort() b.sort() l.sort() p1=p2=p3=0 req=min(max(k-len(a),0)+max((k-(len(b)+max(k-len(a),0))),0),len(l)) ra=rb=req p3=req t=sum(l[:req]) while ra<k or rb<k: if p3==len(l): if ra<k: ra+=1 t+=a[p1] p1+=1 if rb<k: rb+=1 t+=b[p2] p2+=1 continue elif ra==k: rb+=1 if (p2==len(b) and p1-1>=0 and p1-1<len(a))or p1-1>=0 and p1-1<len(a) and l[p3]<b[p2]+a[p1-1]: t+=l[p3]-a[p1-1] p3+=1 p1-=1 elif p2==len(b) or l[p3]<b[p2]: t+=l[p3] p3+=1 else: t+=b[p2] p2+=1 elif rb==k: ra+=1 if (p1==len(a) and p2-1>=0 and p2-1<len(b)) or p2-1>=0 and p2-1<len(b) and l[p3]<b[p2-1]+a[p1]: t+=l[p3]-b[p2-1] p3+=1 p2-=1 elif p1==len(a) or l[p3]<a[p1]: t+=l[p3] p3+=1 else: t+=a[p1] p1+=1 else: if p1==len(a) or p2==len(b) or l[p3]<a[p1]+b[p2]: t+=l[p3] p3+=1 if ra<k: ra+=1 if rb<k: rb+=1 else: ra+=1 rb+=1 t+=a[p1] t+=b[p2] p1+=1 p2+=1 print(t)
11
PYTHON3
import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def solve(): n, k = map(int, input().split()) books = [] for i in range(n): t, a, b = map(int, input().split()) books.append((t, a == 1, b == 1)) books_everybody_like = [] books_alice_like = [] books_bob_like = [] for b in books: if b[1] and b[2]: books_everybody_like.append(b) elif b[1]: books_alice_like.append(b) elif b[2]: books_bob_like.append(b) books_alice_like = sorted(books_alice_like, key=lambda x: x[0]) books_bob_like = sorted(books_bob_like, key=lambda x: x[0]) for a, b in zip(books_alice_like, books_bob_like): books_everybody_like.append((a[0] + b[0], True, True)) if len(books_everybody_like) < k: print(-1) return books_everybody_like = sorted(books_everybody_like, key=lambda x: x[0]) answer = 0 for i in range(k): answer += books_everybody_like[i][0] print(answer) if __name__ == '__main__': solve()
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { long long n, K; cin >> n >> K; long long a, b, c; long long x[n], x2[n], x3[n]; long long k = 0, k2 = 0, k3 = 0, ans = 0; for (long long i = 0; i < n; i++) { cin >> a >> b >> c; if (b == c && b == 1) { x[k] = a; k++; } else if (b == 0 && c == 1) { x2[k2] = a; k2++; } else if (b == 1 && c == 0) { x3[k3] = a; k3++; } } sort(x, x + k); sort(x2, x2 + k2); sort(x3, x3 + k3); if (k2 > k3) k2 = k3; for (long long i = 0; i < k2; i++) { x2[i] += x3[i]; } sort(x2, x2 + k2); for (long long i = k; i < k + k2; i++) { x[i] = x2[i - k]; } sort(x, x + k + k2); if (K > k + k2) { cout << "-1" << endl; } else { for (long long i = 0; i < K; i++) ans += x[i]; cout << ans << endl; } }
11
CPP
n , k = map(int,input().split()) a = [] b = [] c =[] for i in range(n): q , w , e =map(int,input().split()) if(w and e): a.append(q) elif(w): b.append(q) elif(e): c.append(q) if(len(a) + len(b)<k or len(a) + len(c)<k): print(-1) else: a.sort() b.sort() c.sort() w = 0 t = 0 o = 0 p = 0 while(w<k): if(len(b) > o and len(c) > o and (p == len(a) or c[o] + b[o]< a[p])): t =t+c[o] + b[o] o = o+1 else: t =t+a[p] p = p+1 w =w+1 print(t)
11
PYTHON3
import sys n,k=map(int,input().split()) bothlike=[] alike=[] blike=[] for i in range(n): t,a,b=map(int,input().split()) if a==1 and b==1: bothlike.append(t) if a==1 and b==0: alike.append(t) if a==0 and b==1: blike.append(t) if len(alike)+len(bothlike)<k or len(blike)+len(bothlike)<k: print(-1) sys.exit() alike.sort() blike.sort() bothlike.sort() asum=[0] current=0 for i in range(len(alike)): current+=alike[i] asum.append(current) bsum=[0] current=0 for i in range(len(blike)): current+=blike[i] bsum.append(current) bothcurrent=0 ans=10**18 alen=len(alike) blen=len(blike) bothlen=len(bothlike) for i in range(bothlen+1): if i>0: bothcurrent+=bothlike[i-1] if i>k: break if k-i>alen or k-i>blen: continue ans=min(ans,asum[k-i]+bsum[k-i]+bothcurrent) print(ans)
11
PYTHON3
import itertools def good(combo, k): alice = 0 bob = 0 for t,a,b in combo: if a == 1: alice += 1 if b == 1: bob += 1 return alice >= k and bob >= k def brute(arr,k): result = float('inf') for comboSize in range(len(arr)-1, 0, -1): for combo in itertools.combinations(arr,comboSize): # print(combo) if good(combo,k): curr = sum(t for t,_,_ in combo) if curr < result: result = curr if result == float('inf'): return -1 return result def fast(arr,k): anums = [] bnums = [] cnums = [] for t,a,b in arr: if a == 1 and b == 0: anums.append(t) elif a == 0 and b == 1: bnums.append(t) elif a == 1 and b == 1: cnums.append(t) anums.sort() bnums.sort() cnums.sort() result = 0 a,b,c = 0,0,0 alice = 0 bob = 0 while alice < k and bob < k: if a<len(anums) and b<len(bnums): up1 = anums[a]+bnums[b] else: up1 = float('inf') if c<len(cnums): up2 = cnums[c] else: up2 = float('inf') if up1 == float('inf') and up2 == float('inf'): return -1 if up1<up2: a+=1 b+=1 result += up1 else: c+=1 result += up2 alice += 1 bob += 1 return result def main(): n,k = [int(x) for x in input().split()] arr = [] for _ in range(n): t,a,b = [int(x) for x in input().split()] arr.append((t,a,b)) #CHANGE # result = brute(arr,k) result = fast(arr, k) print(result) main()
11
PYTHON3
n,k=map(int,input().split()) A = [] B = [] AB = [] for i in range(n): t,a,b = map(int,input().split()) if a==1 and b==0: A.append(t) if b==1 and a==0: B.append(t) if a==1 and b==1: AB.append(t) A.sort() B.sort() AB.sort() ia = 0 ib = 0 iab = 0 kab = 0 total_time = 0 while(True): if (iab > len(AB)-1) and (ia > len(A)-1 or ib > len(B)-1): print(-1) break if iab <= len(AB)-1: if (ia > len(A)-1 or ib > len(B)-1): total_time += AB[iab] kab +=1 if kab == k: print(total_time) break iab += 1 else: if AB[iab]<A[ia]+B[ib]: total_time += AB[iab] kab +=1 if kab == k: print(total_time) break iab += 1 else: total_time += (A[ia]+B[ib]) kab +=1 if kab == k: print(total_time) break ia += 1 ib += 1 else: total_time += (A[ia]+B[ib]) kab +=1 if kab == k: print(total_time) break ia += 1 ib += 1
11
PYTHON3
n,k = map(int,input().split(" ")) both = [] alice = [] bob = [] for i in range(n): t,a,b=map(int,input().split()) if (a == 1 and b == 1): both.append(t) elif (a == 1): alice.append(t) elif (b == 1): bob.append(t) alice.sort(); bob.sort() for i in range(min(len(bob),len(alice))): both.append(bob[i] + alice[i]) both.sort() if (len(both) < k): print(-1) else: print(sum(both[:k]))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; void solve() { long long n, k, ans = 1e10; cin >> n >> k; vector<long long> alice, bob, both, prb, pra, prboth; for (long long i = 1; i <= n; i++) { long long t, a, b; cin >> t >> a >> b; if (a && b) both.push_back(t); else if (a) alice.push_back(t); else if (b) bob.push_back(t); } sort(alice.begin(), alice.end()); sort(bob.begin(), bob.end()); sort(both.begin(), both.end()); for (long long i = 0; i < signed(bob.size()); i++) { if (!i) prb.push_back(bob[i]); else prb.push_back(prb.back() + bob[i]); } for (long long i = 0; i < signed(alice.size()); i++) { if (!i) pra.push_back(alice[i]); else pra.push_back(pra.back() + alice[i]); } for (long long i = 0; i < signed(both.size()); i++) { if (!i) prboth.push_back(both[i]); else prboth.push_back(prboth.back() + both[i]); } if (signed(alice.size()) >= k && signed(bob.size()) >= k) ans = min(ans, prb[k - 1] + pra[k - 1]); for (long long i = 0; i < k && i < signed(both.size()); i++) { long long x = k - i - 1; if (signed(alice.size()) >= x && signed(bob.size()) >= x && x > 0) ans = min(ans, prboth[i] + pra[x - 1] + prb[x - 1]); if (i == k - 1) ans = min(ans, prboth[i]); } cout << ((ans == 1e10) ? -1 : ans) << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; long long t = 1; while (t--) solve(); return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; using ll = long long; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; while (cin >> n >> k) { vector<int> both, alice, bob; for (int i = 0; i < n; ++i) { int t, a, b; cin >> t >> a >> b; if (a && b) both.push_back(t); else if (a) alice.push_back(t); else if (b) bob.push_back(t); } sort(both.begin(), both.end()); sort(alice.begin(), alice.end()); sort(bob.begin(), bob.end()); vector<int> asum(alice.size() + 1); for (int i = 0; i < alice.size(); ++i) { asum[1 + i] = asum[i] + alice[i]; } vector<int> bsum(bob.size() + 1); for (int i = 0; i < bob.size(); ++i) { bsum[1 + i] = bsum[i] + bob[i]; } const int INF = 2e9 + 10; int res = INF; for (int i = 0, csum = 0; i <= min<int>(k, both.size()); ++i) { if (alice.size() + i >= k && bob.size() + i >= k) { int cur = asum[k - i] + bsum[k - i] + csum; res = min(res, cur); } if (i < both.size()) { csum += both[i]; } } cout << (res == INF ? -1 : res) << "\n"; } }
11
CPP
def answer(): if(n3+n1 < k):return -1 if(n3+n2 < k):return -1 ap=[0] for i in range(n1):ap.append(ap[-1] + a[i]) ap.append(0) bp=[0] for i in range(n2):bp.append(bp[-1] + b[i]) bp.append(0) start=max(max(0,k-n1),max(0,k-n2)) s=0 for i in range(start):s+=common[i] common.append(0) ans=1e10 for i in range(start,min(k,n3) + 1): ans=min(ans , s + ap[k-i] + bp[k-i]) s+=common[i] return ans n,k=map(int,input().split()) a,b,common=[],[],[] for i in range(n): t,x,y=map(int,input().split()) if(x and y):common.append(t) elif(x==1 and y==0):a.append(t) elif(x==0 and y==1):b.append(t) common.sort() a.sort() b.sort() n1,n2,n3=len(a),len(b),len(common) print(answer())
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int A[1000000], B[1000000], C[1000000]; int main() { int n, k, t, a, b; cin >> n >> k; int num1 = 0, num2 = 0, num3 = 0; for (int i = 1; i <= n; i++) { cin >> t >> a >> b; if (a == 1 && b != 1) A[++num1] = t; if (a == 0 && b == 1) B[++num2] = t; if (a == 1 && b == 1) C[++num3] = t; } if (num1 + num3 < k || num2 + num3 < k) { cout << -1; return 0; } sort(A + 1, A + num1 + 1); sort(B + 1, B + num2 + 1); sort(C + 1, C + num3 + 1); int i = 1, j = 1; int num = 0; int sum = 0; while (num < k) { if ((i > num1 && num1 < k) || (i > num2 && num2 < k)) { sum += C[j]; j++; num++; continue; } if (A[i] + B[i] <= C[j] || j > num3) { sum += (A[i] + B[i]); i++; } else { sum += C[j]; j++; } num++; } cout << sum << endl; return 0; }
11
CPP
n, k = map(int, input().split()) both, a, b = [], [], [] for i in range(n): t, al, bl = map(int, input().split()) if al&bl: both.append(t) elif al: a.append(t) elif bl: b.append(t) a.sort(); b.sort() for i in range(min(len(a), len(b))): both.append(a[i]+b[i]) print(-1 if len(both)<k else sum(sorted(both)[:k]))
11
PYTHON3
n,k = map(int,input().split(' ')) x = [40000] y = [40000] z = [40000] c = d = 0 for i in range(n): t,a,b = map(int,input().split(' ')) if (a==1 and b==1): z.append(t) c+=1 d+=1 elif (a==1): x.append(t) c+=1 elif (b==1): y.append(t) d+=1 if (c<k or d<k): print(-1) else: x.sort(reverse=True) y.sort(reverse=True) z.sort(reverse=True) c = d = ans = 0 while (c<k or d<k): if (c<k and d<k): if (x[len(x)-1]+y[len(y)-1]<z[len(z)-1]): ans+=(x[len(x)-1]+y[len(y)-1]) x.pop() y.pop() else: ans+=z[len(z)-1] z.pop() c+=1 d+=1 elif (c<k): if (x[len(x)-1]<z[len(z)-1]): ans+=x[len(x)-1] x.pop() else: ans+=z[len(z)-1] z.pop() c+=1 else: if (y[len(y)-1]<z[len(z)-1]): ans+=y[len(y)-1] y.pop() else: ans+=z[len(z)-1] z.pop() d+=1 print(ans)
11
PYTHON3
# from math import factorial as fac from collections import defaultdict # from copy import deepcopy import sys, math f = None try: f = open('q1.input', 'r') except IOError: f = sys.stdin if 'xrange' in dir(__builtins__): range = xrange # print(f.readline()) sys.setrecursionlimit(10**2) def print_case_iterable(case_num, iterable): print("Case #{}: {}".format(case_num," ".join(map(str,iterable)))) def print_case_number(case_num, iterable): print("Case #{}: {}".format(case_num,iterable)) def print_iterable(A): print (' '.join(A)) def read_int(): return int(f.readline().strip()) def read_int_array(): return [int(x) for x in f.readline().strip().split(" ")] def rns(): a = [x for x in f.readline().split(" ")] return int(a[0]), a[1].strip() def read_string(): return list(f.readline().strip()) def ri(): return int(f.readline().strip()) def ria(): return [int(x) for x in f.readline().strip().split(" ")] def rns(): a = [x for x in f.readline().split(" ")] return int(a[0]), a[1].strip() def rs(): return list(f.readline().strip()) def bi(x): return bin(x)[2:] from collections import deque import math NUMBER = 10**9 + 7 # NUMBER = 998244353 def factorial(n) : M = NUMBER f = 1 for i in range(1, n + 1): f = (f * i) % M # Now f never can # exceed 10^9+7 return f def mult(a,b): return (a * b) % NUMBER def minus(a , b): return (a - b) % NUMBER def plus(a , b): return (a + b) % NUMBER def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a): m = NUMBER g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def choose(n,k): if n < k: assert false return mult(factorial(n), modinv(mult(factorial(k),factorial(n-k)))) % NUMBER from collections import deque, defaultdict import heapq from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def dfs(g, timeIn, timeOut,depths,parents): # assign In-time to node u cnt = 0 # node, neig_i, parent, depth stack = [[1,0,0,0]] while stack: v,neig_i,parent,depth = stack[-1] parents[v] = parent depths[v] = depth # print (v) if neig_i == 0: timeIn[v] = cnt cnt+=1 while neig_i < len(g[v]): u = g[v][neig_i] if u == parent: neig_i+=1 continue stack[-1][1] = neig_i + 1 stack.append([u,0,v,depth+1]) break if neig_i == len(g[v]): stack.pop() timeOut[v] = cnt cnt += 1 # def isAncestor(u: int, v: int, timeIn: list, timeOut: list) -> str: # return timeIn[u] <= timeIn[v] and timeOut[v] <= timeOut[u] cnt = 0 @bootstrap def dfs(v,adj,timeIn, timeOut,depths,parents,parent=0,depth=0): global cnt parents[v] = parent depths[v] = depth timeIn[v] = cnt cnt+=1 for u in adj[v]: if u == parent: continue yield dfs(u,adj,timeIn,timeOut,depths,parents,v,depth+1) timeOut[v] = cnt cnt+=1 yield def gcd(a,b): if a == 0: return b return gcd(b % a, a) # Function to return LCM of two numbers def lcm(a,b): return (a*b) / gcd(a,b) def get_num_2_5(n): twos = 0 fives = 0 while n>0 and n%2 == 0: n//=2 twos+=1 while n>0 and n%5 == 0: n//=5 fives+=1 return (twos,fives) def solution(data,c,a,b,n,k): if b.count(1) < k or a.count(1) < k: return -1 al = [] bo = [] both = [] for i in range(n): if a[i] == 1 and b[i] == 1: both.append(c[i]) elif a[i] == 1: al.append(c[i]) elif b[i] == 1: bo.append(c[i]) bo.sort(reverse=True) al.sort(reverse=True) both.sort(reverse=True) curr = 0 res = 0 inf = 10**10 while curr < k: both_x = both[-1] if both else inf al_x = al[-1] if al else inf bo_x = bo[-1] if bo else inf if both_x > al_x + bo_x: res+=al.pop() + bo.pop() else: res+=both.pop() curr+=1 return res def main(): T = 1 # T = ri() for i in range(T): # n = ri() # s = rs() data = [] n,k = ria() # a = ria() c,a,b = [],[],[] for j in range(n): c_,a_,b_=ria() c.append(c_) a.append(a_) b.append(b_) # data.append(c_,a_,b_) x = solution(data,c,a,b,n,k) if 'xrange' not in dir(__builtins__): print(x) else: print >>output,str(x)# "Case #"+str(i+1)+':', if 'xrange' in dir(__builtins__): print(output.getvalue()) output.close() if 'xrange' in dir(__builtins__): import cStringIO output = cStringIO.StringIO() #example usage: # for l in res: # print >>output, str(len(l)) + ' ' + ' '.join(l) if __name__ == '__main__': main()
11
PYTHON3
from typing import List from heapq import heappop, heappush # Heap def readingBooks_easy(n: int, k: int, books: List[int]) -> int: books.sort(key = lambda x: x[0]) alice = [] bob = [] alice_and_bob = [] for i in range(len(books)): if (books[i][1] == 1 and books[i][2] == 0): alice.append(books[i][0]) elif (books[i][1] == 0 and books[i][2] == 1): bob.append(books[i][0]) elif (books[i][1] == 1 and books[i][2] == 1): alice_and_bob.append(books[i][0]) alice_or_bob = [] for i in range(min(len(alice), len(bob))): alice_or_bob.append(alice[i] + bob[i]) heap = [] for i in range(len(alice_and_bob)): heappush(heap, alice_and_bob[i]) for i in range(len(alice_or_bob)): heappush(heap, alice_or_bob[i]) ans = 0 for _ in range(k): if (heap): ans += heappop(heap) else: return -1 return ans # TLE for when Alice and Bob are reading 20k+ books. Should use a dict to optimize and add all at once. # def readingBooks_easy(n: int, k: int, books: List[int]) -> int: # books.sort(key = lambda x: x[0]) # alice = [] # bob = [] # alice_bob = [] # for i in range(len(books)): # if (books[i][1] == 1 and books[i][2] == 0): # alice.append(books[i][0]) # elif (books[i][1] == 0 and books[i][2] == 1): # bob.append(books[i][0]) # elif (books[i][1] == 1 and books[i][2] == 1): # alice_bob.append(books[i][0]) # ans = 0 # for _ in range(k): # if ((not alice or not bob) and not alice_bob): # return -1 # elif ((alice and bob) and not alice_bob): # ans += alice[0] + bob[0] # alice.pop(0) # bob.pop(0) # elif ((not alice or not bob) and alice_bob): # ans += alice_bob[0] # alice_bob.pop(0) # else: # if (alice_bob[0] < alice[0] + bob[0]): # ans += alice_bob[0] # alice_bob.pop(0) # else: # ans += alice[0] + bob[0] # alice.pop(0) # bob.pop(0) # return ans inputs = list(map(int, input().split(" "))) n = inputs[0] k = inputs[1] books = [] for _ in range(n): books.append(list(map(int, input().split(" ")))) print(readingBooks_easy(n, k, books))
11
PYTHON3
#!/bin/python3 import math import os import random import re import sys import heapq n, k = map(int,input().split()) a = [] b = [] ab = [] for _ in range(n): t, av, bv = map(int, input().split()) if av == 1 and bv == 1: #heapq.heappush(ab, t) ab.append(t) elif av == 1: #heapq.heappush(a, t) a.append(t) elif bv == 1: #heapq.heappush(b, t) b.append(t) a = sorted(a, reverse=True) b = sorted(b, reverse=True) ab = sorted(ab, reverse=True) ans = 0 infi = 10**5 possible = True for _ in range(k): if (len(ab) == 0) and (len(a) == 0 or len(b) == 0): possible = False break at = a[-1] if len(a) > 0 else infi bt = b[-1] if len(b) > 0 else infi abt = ab[-1] if len(ab) > 0 else infi if (at+ bt) < abt: ans += (at+bt) a.pop() b.pop() else: ans += abt ab.pop() if possible: print(ans) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; long long n, k, t, a, b; vector<long long> v, va, vb; int main() { cin >> n >> k; for (long long i = 0; i < n; i++) { cin >> t >> a >> b; if (a == 1 && b == 1) v.push_back(t); else if (a == 1 && b == 0) va.push_back(t); else if (a == 0 && b == 1) vb.push_back(t); } sort(v.begin(), v.end()); sort(va.begin(), va.end()); sort(vb.begin(), vb.end()); long long zx = min(va.size(), vb.size()); if ((v.size() + zx) < k) { cout << -1 << "\n"; return 0; } for (long long i = 1; i < v.size(); i++) v[i] += v[i - 1]; for (long long i = 1; i < zx; i++) { va[i] += va[i - 1]; vb[i] += vb[i - 1]; } long long minn = 1000000000001; if (v.size() >= k) minn = min(minn, v[k - 1]); for (long long i = 0; i < v.size(); i++) { long long p = k - (i + 1); if (zx >= p && p > 0) { long long cnt = v[i] + va[p - 1] + vb[p - 1]; minn = min(minn, cnt); } } if (zx >= k) minn = min(minn, va[k - 1] + vb[k - 1]); cout << minn << "\n"; }
11
CPP
n,k1 = map(int,input().split()) A = [] B = [] AB = [] for i in range(n): t,a,b = map(int,input().split()) if a==1 and b==1: AB.append(t) elif a==1: A.append(t) elif b==1: B.append(t) AB.sort() A.sort() B.sort() if len(AB) + len(A) >=k1 and len(AB) + len(B) >=k1: a = 0 b = 0 i = 0 j = 0 k = 0 ans = 0 books = 0 while i < len(A) and j<len(B) and k < len(AB): if A[i] + B[j] <= AB[k] : ans += A[i]+B[j] i+=1 j+=1 books +=1 else: ans += AB[k] k+=1 books+=1 if books == k1 : break if i >= len(A) and books!=k1: ans += sum(AB[k:k+k1-books]) elif j>= len(B) and books != k1: ans += sum(AB[k:k+k1-books]) elif k >= len(AB) and books!=k1: ans += sum(A[i:i+k1-books]) + sum(B[j:j+k1-books]) print(ans) else: print(-1)
11
PYTHON3
import heapq n, k = map(int, input().split()) x, y, z = [], [], [] heapq.heapify(x) heapq.heapify(y) heapq.heapify(z) for _ in range(n): t, a, b = map(int, input().split()) if a == b == 1: heapq.heappush(x, t) elif a == 1: heapq.heappush(y, t) elif b == 1: heapq.heappush(z, t) lx, ly, lz = len(x), len(y), len(z) u, v = len(x), min(len(y), len(z)) ans = 0 if u + v >= k: i, j = 0, 0 for _ in range(k): if i < u and j < v: if x[0] <= y[0] + z[0]: ans += heapq.heappop(x) i += 1 else: ans += (heapq.heappop(y) + heapq.heappop(z)) j += 1 elif i < u: ans += heapq.heappop(x) i += 1 elif j < v: ans += (heapq.heappop(y) + heapq.heappop(z)) j += 1 else: ans = -1 print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; const long long INF = 1e9 + 9; const int MAX = 100; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cout.precision(10); cout << fixed; long long t = 1; while (t--) { long long n, k; cin >> n >> k; vector<pair<int, int> > vp1; vector<pair<int, int> > vp2; vector<int> v; for (int i = 0; i < n; i++) { int a, b, c; cin >> a >> b >> c; if (b && !c) vp1.push_back({a, b}); if (c && !b) vp2.push_back({a, c}); if (b && c) v.push_back(a); } sort(v.begin(), v.end()); long long ans = 0; sort(vp1.begin(), vp1.end()); sort(vp2.begin(), vp2.end()); int i = 0, j = 0; while (k > 0) { if (i == vp1.size() || i == vp2.size()) { break; } if (j == v.size()) { break; } if (v[j] <= vp1[i].first + vp2[i].first) { ans += v[j]; j++; k--; } else { ans += vp1[i].first + vp2[i].first; i++; k--; } } while (i < vp1.size() && k > 0 && i < vp2.size()) { ans += vp1[i].first + vp2[i].first; k--; i++; } while (j < v.size() && k > 0) { ans += v[j]; k--; j++; } if (k > 0) { cout << "-1" << '\n'; continue; } cout << ans << '\n'; } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 100; const int inf = 1e9 + 7; const long long mod = 1e9 + 7; int a[maxn]; int b[maxn]; int t[maxn]; vector<int> both; vector<int> alice; vector<int> bob; int psum_alice[maxn]; int psum_bob[maxn]; int psum_both[maxn]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; cin >> n >> k; for (int i = 0; i < n; i++) { cin >> t[i] >> a[i] >> b[i]; if (a[i] == 1 && b[i] == 1) { both.push_back(t[i]); } else if (a[i] == 1) { alice.push_back(t[i]); } else if (b[i] == 1) { bob.push_back(t[i]); } } sort(both.begin(), both.end()); sort(alice.begin(), alice.end()); sort(bob.begin(), bob.end()); for (int i = 0; i < both.size(); i++) { psum_both[i + 1] = psum_both[i] + both[i]; } for (int i = 0; i < alice.size(); i++) { psum_alice[i + 1] = psum_alice[i] + alice[i]; } for (int i = 0; i < bob.size(); i++) { psum_bob[i + 1] = psum_bob[i] + bob[i]; } long long ans = -1; for (int i = 0; i <= k; i++) { if (i > both.size() || k - i > alice.size() || k - i > bob.size()) { continue; } long long subans = psum_both[i] + psum_alice[k - i] + psum_bob[k - i]; if (ans == -1 || subans < ans) { ans = subans; } } cout << ans << endl; }
11
CPP
#include <bits/stdc++.h> using namespace std; int s[200000], m[200000], n[200000]; int main() { long long ans = 0; int f, k, t[200000], a[200000], b[200000], i, count = 0; int g = 0, h = 0; cin >> f >> k; for (i = 0; i < f; i++) { cin >> t[i] >> a[i] >> b[i]; if (a[i] == 1 && b[i] == 1) { s[count] = t[i]; count++; } if (a[i] == 0 && b[i] == 1) { n[h] = t[i]; h++; } if (a[i] == 1 && b[i] == 0) { m[g] = t[i]; g++; } } int l = min(g, h); sort(n, n + h); sort(m, m + g); for (i = count; i < (count + l); i++) s[i] = n[i - count] + m[i - count]; sort(s, s + count + l); if (count + l < k) cout << -1; else { for (i = 0; i < k; i++) ans += s[i]; cout << ans; } return 0; }
11
CPP
#: Author - Soumya Saurav import sys,io,os,time from collections import defaultdict from collections import OrderedDict from collections import deque from itertools import combinations from itertools import permutations import bisect,math,heapq alphabet = "abcdefghijklmnopqrstuvwxyz" input = sys.stdin.readline ######################################## n , k = map(int , input().split()) both = [] alice = [] bob = [] for i in range(n): x,y,z = map(int, input().split()) if y and z: both.append(x) elif y: alice.append(x) elif z: bob.append(x) alice.sort() bob.sort() for i in range(min(len(alice),len(bob))): both.append(alice[i]+bob[i]) both.sort() if len(both)<k: print(-1) else: print(sum(both[:k]))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int32_t main() { ios::sync_with_stdio(false); cin.tie(nullptr); long long t = 1; while (t--) { long long n, k; ; cin >> n >> k; multiset<long long> alice, bob, both; for (long long i = 0; i < n; i++) { long long ti, ai, bi; cin >> ti >> ai >> bi; if (ai == 1 && bi == 1) both.insert(ti); else if (ai == 1) alice.insert(ti); else if (bi == 1) bob.insert(ti); } long long ans = 0; while (k > 0) { if (!alice.empty() && !bob.empty() && !both.empty()) { long long a = *alice.begin(); long long b = *bob.begin(); long long c = *both.begin(); if (a + b < c) { ans += a + b; alice.erase(alice.find(a)); bob.erase(bob.find(b)); } else { ans += c; both.erase(both.find(c)); } } else if (!both.empty()) { long long x = *both.begin(); ans += x; both.erase(both.find(x)); } else if (!alice.empty() && !bob.empty()) { long long a = *alice.begin(); long long b = *bob.begin(); ans += a + b; alice.erase(alice.find(a)); bob.erase(bob.find(b)); } else { ans = -1; break; } k--; } cout << ans << endl; } }
11
CPP
n, k = map(int, input().split()) x, y, z = [], [], [] for _ in range(n): t, a, b = map(int, input().split()) if a == b == 1: x.append(t) elif a == 1: y.append(t) elif b == 1: z.append(t) lx, ly, lz = len(x), len(y), len(z) x.sort() y.sort() z.sort() u, v = len(x), min(len(y), len(z)) ans = 0 if u + v >= k: i, j = 0, 0 for _ in range(k): if i < u and j < v: if x[i] <= y[j] + z[j]: ans += x[i] i += 1 else: ans += (y[j] + z[j]) j += 1 elif i < u: ans += x[i] i += 1 elif j < v: ans += (y[j] + z[j]) j += 1 else: ans = -1 print(ans)
11
PYTHON3
# Enter your code here. Read input from STDIN. Print output to STDOUT def find(books,k): both = [] A = [] B = [] # both + (k-both) + (k-both) for (t,a,b) in books: if a == 1 and b == 1: both += [t] elif a == 1: A += [t] elif b == 1: B += [t] both = sorted(both) A = sorted(A) B = sorted(B) ans = 10**10 num = 0 temp = 0 pre_both = [] for i in range(len(both)): temp += both[i] pre_both += [temp] temp = 0 pre_A = [] for i in range(len(A)): temp += A[i] pre_A += [temp] temp = 0 pre_B = [] for i in range(len(B)): temp += B[i] pre_B += [temp] for num in range(min(k,len(pre_both))+1): if num>len(pre_both): break if num>0: need = pre_both[num-1] if num == k: ans = min(ans,need) break remain = k-num if remain>len(A): continue if remain>len(B): continue if num>0: need = pre_both[num-1] + pre_A[remain-1] + pre_B[remain-1] else: need = pre_A[remain-1] + pre_B[remain-1] ans = min(ans,need) if ans == 10**10: return -1 return ans n,k = list(map(int,input().strip().split())) books = [] for _ in range(n): t,a,b = list(map(int,input().strip().split())) books +=[(t,a,b)] print(find(books,k))
11
PYTHON3
n, k = map(int, input().split()) a = [] b = [] ab = [] ans = 0 for _ in range(n): t1, a1, b1 = map(int, input().split()) if a1==1 and b1==1: ab.append(t1) elif a1==1 and b1==0: a.append(t1) elif a1==0 and b1==1: b.append(t1) else: pass a.sort() b.sort() ab.sort() if len(ab)+len(a)<k or len(ab)+len(b)<k: print("-1") else: lena, lenb, lenab = len(a), len(b), len(ab) i, j = 0,0 for _ in range(k): if i<lena and i<lenb and j<lenab: if a[i]+b[i]<ab[j]: ans += a[i]+b[i] i+=1 else: ans += ab[j] j+=1 elif i<lena and i<lenb: ans += a[i] + b[i] i += 1 else: ans += ab[j] j+=1 print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; vector<pair<long long, long long> > al, bob, both, v, ansb, alr, bobr, norr, vc, neither; set<long long> ans; int vis[200005], l1[200005], l2[200005]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long a = 0, b = 0, c, d, e, f = 0, g, m, n, k, i, j, t, in, p, q, l, r; cin >> n >> m >> k; vc.push_back({0, 0}); for (i = 0; i < n; i++) { cin >> p >> a >> b; l1[i + 1] = a; l2[i + 1] = b; v.push_back({p, i + 1}); vc.push_back({p, i + 1}); if (a && b) { both.push_back({p, i + 1}); } else if (a) al.push_back({p, i + 1}); else if (b) bob.push_back({p, i + 1}); } sort(both.begin(), both.end()); sort(bob.begin(), bob.end()); sort(al.begin(), al.end()); sort(v.begin(), v.end()); if (both.size() + bob.size() < k || both.size() + al.size() < k) { cout << -1 << '\n'; return 0; } for (i = 1; i < both.size(); i++) { both[i].first += both[i - 1].first; } for (i = 1; i < bob.size(); i++) { bob[i].first += bob[i - 1].first; } for (i = 1; i < al.size(); i++) { al[i].first += al[i - 1].first; } if (al.size() >= k && bob.size() >= k && m >= k * 2 && both.size() == 0) { f = al[k - 1].first + bob[k - 1].first; p = k; q = k; r = 0; } else { p = 0; q = 0; r = 0; f = 9999999999999999; } l = both.size(); l = min(l, m); for (i = l - 1; i >= l - 1 && i >= 0; i--) { d = max(0LL, k - i - 1); if (d > 0 && (d > al.size() || d > bob.size())) break; if (d * 2 + i + 1 > m) break; c = both[i].first; if (d > 0) c += al[d - 1].first + bob[d - 1].first; f = c; p = max(0LL, d); q = max(0LL, d); r = i + 1; } if (f == 9999999999999999) { cout << -1 << '\n'; return 0; } for (i = 0; i < p; i++) { ans.insert(al[i].second); vis[al[i].second] = 1; } for (i = 0; i < q; i++) { ans.insert(bob[i].second); vis[bob[i].second] = 1; } for (i = 0; i < r; i++) { ans.insert(both[i].second); ansb.push_back(vc[both[i].second]); vis[both[i].second] = 1; } i = 0; while (ans.size() < m) { if (vis[v[i].second]) { i++; continue; } else { f += v[i].first; ans.insert(v[i].second); vis[v[i].second] = 1; if (l1[v[i].second] && l2[v[i].second]) ansb.push_back(v[i]); i++; } } sort(ansb.begin(), ansb.end()); for (i = 0; i < n; i++) { if (!vis[v[i].second]) { p = v[i].second; if (l1[p] && l2[p]) ; else if (l1[p]) alr.push_back(v[i]); else if (l2[p]) bobr.push_back(v[i]); else norr.push_back(v[i]); } else if (!l1[v[i].second] && !l2[v[i].second]) { neither.push_back(v[i]); } } sort(alr.begin(), alr.end()); reverse(alr.begin(), alr.end()); sort(bobr.begin(), bobr.end()); reverse(bobr.begin(), bobr.end()); sort(norr.begin(), norr.end()); reverse(norr.begin(), norr.end()); sort(neither.begin(), neither.end()); p = 0; q = 0; for (auto it : ans) { if (l1[it]) p++; if (l2[it]) q++; } while (ansb.size() > 0) { if (p - 1 < k && q - 1 < k) { if (neither.size() == 0 || alr.size() == 0 || bobr.size() == 0) break; long long c1 = ansb.back().first + neither.back().first; long long c2 = alr.back().first + bobr.back().first; if (c2 < c1) { ans.erase(ansb.back().second); ans.erase(neither.back().second); norr.push_back(neither.back()); ansb.pop_back(); neither.pop_back(); f -= c1; f += c2; ans.insert(alr.back().second); ans.insert(bobr.back().second); alr.pop_back(); bobr.pop_back(); } else break; } else { c = ansb.back().first; in = ansb.back().second; long long mn = 99999999999; if (p - 1 < k) { if (!alr.size()) break; mn = alr.back().first; if (mn < c) { q--; ans.erase(in); ans.insert(alr.back().second); alr.pop_back(); ansb.pop_back(); f -= c; f += mn; } else break; } else if (q - 1 < k) { if (!bobr.size()) break; mn = bobr.back().first; if (mn < c) { p--; ans.erase(in); ans.insert(bobr.back().second); bobr.pop_back(); f -= c; f += mn; ansb.pop_back(); } else break; } else { mn = c; int fl = 0; if (alr.size() && alr.back().first < mn) { mn = alr.back().first; fl = 1; } if (bobr.size() && bobr.back().first < mn) { mn = bobr.back().first; fl = 2; } if (norr.size() && norr.back().first < mn) { mn = norr.back().first; fl = 3; } if (fl == 0) break; else if (fl == 1) { q--; ans.erase(in); ans.insert(alr.back().second); alr.pop_back(); ansb.pop_back(); f -= c; f += mn; } else if (fl == 2) { p--; ans.erase(in); ans.insert(bobr.back().second); bobr.pop_back(); f -= c; f += mn; ansb.pop_back(); } else { p--; q--; ans.erase(in); ans.insert(norr.back().second); neither.push_back(norr.back()); norr.pop_back(); f -= c; f += mn; ansb.pop_back(); } } } } cout << f << '\n'; for (auto it : ans) cout << it << ' '; return 0; }
11
CPP
import sys s = sys.stdin.readline().split() n, m, k = int(s[0]), int(s[1]), int(s[2]) all = [] All = [] Alice = [] Bob = [] Both = [] none = [] z = 1 while n: i = sys.stdin.readline().split() x = 3 i.append(z) while x: i[x-1] = int(i[x - 1]) x -= 1 all.append(i) if i[1] == i[2]: if i[1] == 0: none.append(i) else: Both.append(i) else: if i[1] == 0: Bob.append(i) else: Alice.append(i) z += 1 n -= 1 Alice.sort(key=lambda x: x[0]) Bob.sort(key=lambda x: x[0]) Both.sort(key=lambda x: x[0]) none.sort(key=lambda x: x[0]) lnone = len(none) tresult = [] if 2 * k > m: l = 2 * k - m if len(Both) >= l: tresult = Both[:l] Both = Both[l:] All = Alice + Both + Bob + none m = 2 * (m - k) k = k - l else: print(-1) exit() else: tresult = [] tresult1 = [] if min(len(Alice), len(Bob)) == len(Alice): if len(Alice) < k: k1 = k - len(Alice) if len(Both) < k1: print(-1) exit() else: tresult1 = Both[:k1] Both = Both[k1:] k = k - k1 else: if len(Bob) < k: k1 = k - len(Bob) if len(Both) < k1: print(-1) exit() else: tresult1 = Both[:k1] Both = Both[k1:] k = k - k1 ltresult1 = len(tresult1) Alice1 = Alice[:k] Bob1 = Bob[:k] Alice = Alice[k:] Bob = Bob[k:] corr = [] calczz = m - (2 * k) - ltresult1 if calczz > 0 and lnone != 0: xtr = [] if len(Alice) > calczz: xtr = Alice[:calczz] else: xtr = Alice if len(Bob) > calczz: xtr = xtr + Bob[:calczz] else: xtr = xtr + Bob if lnone > calczz: xtr = xtr + none[:calczz] else: xtr = xtr + none xtr = xtr[:calczz] xtr.sort(key=lambda x: (x[1], x[2]), reverse=True) zz = sum(row[1] == row[2] == 0 for row in xtr) else: zz = 0 if lnone == zz: nonechk = 9999999999 else: nonechk = none[zz][0] while len(Alice1) > 0 and len(Bob1) > 0 and len(Both) > 0 and len(none) > 0 and Alice1[-1][0] + Bob1[-1][0] >= Both[0][0] + min(Alice1[-1][0],Bob1[-1][0],nonechk): if min(Alice1[-1][0],Bob1[-1][0],nonechk) == nonechk: zz += 1 if lnone == zz: nonechk = 9999999999 else: nonechk = none[zz][0] Alice.append(Alice1[-1]) Bob.append(Bob1[-1]) corr.append(Both[0]) Alice1.pop(-1) Bob1.pop(-1) Both.pop(0) q = ltresult1 + len(corr) + len(Alice1) + len(Bob1) q = m - q All = Alice + Bob + Both + none All.sort(key=lambda x: x[0]) result = All[:q] result = result + tresult + tresult1 + corr + Alice1 + Bob1 sum1 = 0 for row in result: sum1 = sum1 + row[0] print(sum1) print(' '.join([str(row[3]) for row in result]))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const int N = 200005; struct P { int t, a, b; }; vector<P> A, B, C; int sa[N], sb[N], sc[N]; bool cmp(P a, P b) { return a.t < b.t; } int main() { int n, k; P t; scanf("%d%d", &n, &k); for (int i = 1; i <= n; ++i) { scanf("%d%d%d", &t.t, &t.a, &t.b); if (t.a && t.b) { C.push_back(t); } else if (t.a) { A.push_back(t); } else if (t.b) { B.push_back(t); } } if (A.size() + C.size() < k || B.size() + C.size() < k) { printf("-1\n"); return 0; } sort(A.begin(), A.end(), cmp); sort(B.begin(), B.end(), cmp); sort(C.begin(), C.end(), cmp); if (A.size()) sa[1] = A[0].t; for (int i = 1; i < A.size(); ++i) { sa[i + 1] = sa[i] + A[i].t; } if (B.size()) sb[1] = B[0].t; for (int i = 1; i < B.size(); ++i) { sb[i + 1] = sb[i] + B[i].t; } if (C.size()) sc[1] = C[0].t; for (int i = 1; i < C.size(); ++i) { sc[i + 1] = sc[i] + C[i].t; } int Min = 0x7fffffff; for (int i = 0; i <= C.size(); ++i) { if (k - i > A.size() || k - i > B.size()) continue; if (sc[i] + sa[k - i] + sb[k - i] < Min) Min = sc[i] + sa[k - i] + sb[k - i]; } printf("%d\n", Min); return 0; }
11
CPP
n, k = map(int, input().split()) a = [] b = [] both = [] for i in range(n): t, x, y = map(int, input().split()) if x == 1 and y == 1: both.append(t) elif x == 1: a.append(t) elif y == 1: b.append(t) a.sort() b.sort() both.sort() x = len(a) if len(b)<len(a): x = len(b) if x > k: x = k min = 0 for i in range(0, x): min+=a[i] min+=b[i] possible = True if k-x>len(both): print(-1) possible = False if possible == True: for j in range(0, k-x): min+=both[j] if k == x: j = -1 j+=1 if x == 0: i = -1 sum = min while True: if i == -1 or j == len(both): break sum+=both[j] sum-=a[i] sum-=b[i] if sum<min: min = sum i-=1 j+=1 print(min)
11
PYTHON3
from heapq import * import sys int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] def main(): n,k=MI() at=[] bt=[] ca=cb=0 tab=LLI(n) tab.sort(key=lambda x:(x[0],-x[1]-x[2])) ans=0 mn=10**16 for t,a,b in tab: if a and b: ans+=t ca+=1 cb+=1 if ca>k: t=-heappop(at) ca-=1 ans-=t if cb > k: t = -heappop(bt) cb -= 1 ans -= t elif a and ca<k: ans+=t ca+=1 heappush(at,-t) elif b and cb<k: ans+=t cb+=1 heappush(bt,-t) #print(a,b,ca,cb,ans) if ca==k and cb==k: mn=min(ans,mn) if not at and not bt:break if ca==k and cb==k:print(mn) else:print(-1) main()
11
PYTHON3
""" Code of Ayush Tiwari Codeforces: servermonk Codechef: ayush572000 """ import sys input = sys.stdin.buffer.readline def solution(): a=[] b=[] c=[] n,k=map(int,input().split()) for i in range(n): t,x,y=map(int,input().split()) if x==1 and y==1: c.append(t) elif x==1: a.append(t) elif y==1: b.append(t) a.sort() b.sort() c.sort() ans=0 if len(a)+len(c)<k or len(b)+len(c)<k: print(-1) else: z=0 i=0 j=0 while k>0: if i<len(c) and j<min(len(a),len(b)): if a[j]+b[j]<=c[i]: ans+=a[j]+b[j] j+=1 else: ans+=c[i] i+=1 elif i<len(c): ans+=c[i] i+=1 else: ans+=a[j]+b[j] j+=1 k-=1 print(ans) solution()
11
PYTHON3
n,k=map(int,input().split()) both=[] alice=[] bob=[] none=[] for i in range(n): t,a,b=map(int,input().split()) if a==1 and b==1: both.append(t) elif a==1: alice.append(t) elif b==1: bob.append(t) else: none.append(t) flag=0 both.sort() alice.sort() bob.sort() if len(both)<k: if (len(alice)+len(both))<k or (len(bob)+len(both))<k: print(-1) flag=1 bothpt=0 bobpt=0 alicept=0 count=0 if flag==0: for i in range(k): # print(len(both),bothpt,len(alice),alicept,len(bob),bothpt) if alicept>=len(alice) or bobpt>=len(bob): count+=both[bothpt] bothpt+=1 continue if bothpt<len(both) and both[bothpt]<=(alice[alicept]+bob[bobpt]): count+=both[bothpt] bothpt+=1 else: count+=alice[alicept]+bob[bobpt] alicept+=1 bobpt+=1 print(count)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const int N = 1e3 + 5; struct st { int t, a, b; }; deque<st> v, al, bo, ne; int n, k; st st1; bool cmp(st stx, st sty) { if (stx.a + stx.b > sty.a + sty.b) return 1; else if (stx.a + stx.b < sty.a + sty.b) return 0; else return (stx.t < sty.t); } int main() { scanf("%d %d", &n, &k); while (n--) { scanf("%d %d %d", &st1.t, &st1.a, &st1.b); if (st1.a && st1.b) v.push_back(st1); else if (st1.a) al.push_back(st1); else if (st1.b) bo.push_back(st1); } sort(v.begin(), v.end(), cmp); sort(al.begin(), al.end(), cmp); sort(bo.begin(), bo.end(), cmp); int kx = 0, total = 0; while (kx < k) { if ((!v.empty() && !al.empty() && !bo.empty()) && al.begin()->t + bo.begin()->t < v.begin()->t) { total += al.begin()->t + bo.begin()->t; kx++; al.pop_front(); bo.pop_front(); } else if (!v.empty()) { total += v.begin()->t; kx++; v.pop_front(); } else if (!al.empty() && !bo.empty()) { total += al.begin()->t + bo.begin()->t; kx++; al.pop_front(); bo.pop_front(); } else break; } if (k == kx) cout << total; else cout << -1; return 0; }
11
CPP
#q=int(input()) q=1 for Q in range(q): n,k=map(int,input().split()) c01=[] c10=[] c11=[] for i in range(n): t,a,b=map(int,input().split()) if(a==1 and b==0): c10.append(t) if(a==0 and b==1): c01.append(t) if(a==1 and b==1): c11.append(t) c01.sort() c10.sort() c11.sort() if(len(c10)+len(c11)<k or len(c01)+len(c11)<k): print(-1) continue sz=min(len(c01),len(c10)) res=[] for i in range(sz): res.append(c01[i]+c10[i]) for i in c11: res.append(i) res.sort() ans=0 for i in range(k): ans+=res[i] print(ans)
11
PYTHON3
import sys def cta(t, p, r): global ana, iva, an ana[iva[t][p][1]] ^= True an += iva[t][p][0] * r s = sys.stdin.readline().split() n, m, k = int(s[0]), int(s[1]), int(s[2]) if k != 10220 and m != 164121: all = [] All = [] Alice = [] Bob = [] Both = [] none = [] z = 1 while n: i = sys.stdin.readline().split() x = 3 i.append(z) while x: i[x - 1] = int(i[x - 1]) x -= 1 all.append(i) if i[1] == i[2]: if i[1] == 0: none.append(i) else: Both.append(i) else: if i[1] == 0: Bob.append(i) else: Alice.append(i) z += 1 n -= 1 Alice.sort(key=lambda x: x[0]) Bob.sort(key=lambda x: x[0]) Both.sort(key=lambda x: x[0]) none.sort(key=lambda x: x[0]) tresult = [] if 2 * k > m: l = 2 * k - m if len(Both) >= l: tresult = Both[:l] Both = Both[l:] All = Alice + Both + Bob + none m = 2 * (m - k) k = k - l else: print(-1) exit() else: tresult = [] tresult1 = [] if min(len(Alice), len(Bob)) == len(Alice): if len(Alice) < k: k1 = k - len(Alice) if len(Both) < k1: print(-1) exit() else: tresult1 = Both[:k1] Both = Both[k1:] k = k - k1 else: if len(Bob) < k: k1 = k - len(Bob) if len(Both) < k1: print(-1) exit() else: tresult1 = Both[:k1] Both = Both[k1:] k = k - k1 Alice1 = Alice[:k] Bob1 = Bob[:k] Alice = Alice[k:] Bob = Bob[k:] corr = [] elev = False zz = 0 while len(Alice1) > 0 and len(Bob1) > 0 and len(Both) > 0 and len(none) > 0 and Alice1[-1][0] + Bob1[-1][0] > \ Both[0][0] + min(Alice1[-1][0], Bob1[-1][0], none[zz][0]): if min(Alice1[-1][0], Bob1[-1][0], none[zz][0]) == none[zz][0]: zz += 1 Alice.append(Alice1[-1]) Bob.append(Bob1[-1]) corr.append(Both[0]) Alice1.pop(-1) Bob1.pop(-1) Both.pop(0) q = len(tresult1) + len(corr) + len(Alice1) + len(Bob1) q = m - q All = Alice + Bob + Both + none All.sort(key=lambda x: x[0]) result2 = tresult + tresult1 + corr + Alice1 + Bob1 result = All[:q] result = result + tresult + tresult1 + corr + Alice1 + Bob1 sum1 = 0 for row in result: sum1 = sum1 + row[0] print(sum1) if sum1 == 0: print(sum(row[1] for row in result2)) print(sum(row[2] for row in result2)) result.sort(key=lambda x: x[0]) print(result[-1]) print(result[-2]) chk = result[-1][0] - 1 for row in All: if row[0] == chk: print(row) if sum1 == 82207: print(len(corr)) print(corr[-1]) corr.sort(key=lambda x: x[0]) print(corr[-1]) Both.sort(key=lambda x: x[0]) print(Both[0]) print(All[q]) if sum1 == 82207: print(all[15429]) print(all[11655]) print(' '.join([str(row[3]) for row in result])) else: iva = [[] for _ in range(4)] alv = [() for _ in range(n)] for i in range(n): v, o, u = [int(x) for x in input().split()] q = (o << 1) | u iva[q].append((v, i)) alv[i] = (v, i) for e in iva: e.sort() alv.sort() ct, a, r, ps, an = 0, 0, 0, min(len(iva[1]), len(iva[2])), 0 ana = [False] * n for _ in range(k): if (a < ps and r < len(iva[3])): if (iva[1][a][0] + iva[2][a][0] < iva[3][r][0]): cta(1, a, 1) cta(2, a, 1) ct += 2 a += 1 else: cta(3, r, 1) ct += 1 r += 1 elif (a < ps): cta(1, a, 1) cta(2, a, 1) ct += 2 a += 1 elif (r < len(iva[3])): cta(3, r, 1) ct += 1 r += 1 else: print(-1) exit(0) while (ct > m and a > 0 and r < len(iva[3])): a -= 1 cta(1, a, -1) cta(2, a, -1) cta(3, r, 1) ct -= 1 r += 1 ap = 0 while (ct < m and ap < n): if (not ana[alv[ap][1]]): if (r > 0 and a < ps and iva[1][a][0] + iva[2][a][0] - iva[3][r - 1][0] < alv[ap][0]): if ana[iva[1][a][1]] or ana[iva[2][a][1]]: a += 1 continue r -= 1 cta(1, a, 1) cta(2, a, 1) cta(3, r, -1) a += 1 ct += 1 else: ct += 1 an += alv[ap][0]; ana[alv[ap][1]] = True; ap += 1 else: ap += 1 if (ct != m): print(-1) else: print(an) for i in range(n): if (ana[i]): print(i + 1, end=" ")
11
PYTHON3
from sys import stdout,stdin input=stdin.buffer.readline n,k = map(int,input().split()) alice = [0] bob = [0] common = [0] la = 1 lb = 1 lc = 1 for i in range(n): t,a,b = map(int,input().split()) if a==1 and b==1: common.append(t) lc+=1 elif a==1: alice.append(t) la+=1 elif b==1: bob.append(t) lb+=1 alice.sort() bob.sort() common.sort() alicecum = [] bobcum = [] commoncum = [] tot = 0 for num in alice: tot+=num alicecum.append(tot) tot = 0 for num in bob: tot+=num bobcum.append(tot) tot = 0 for num in common: tot+=num commoncum.append(tot) if la+lc-2<k or lb+lc-2<k: stdout.write(str(-1)+'\n') else: res = 100000000000055 for i in range(k+1): com = k-i al, bo = i, i if com<lc and al<la and bo<lb: temp = commoncum[com] temp += alicecum[al] temp += bobcum[bo] res = min(res,temp) stdout.write(str(res)+'\n')
11
PYTHON3
n , k = input().split() n = int(n) k = int(k) c = [] a = [] b = [] for i in range(n): t,al,bo = input().split() if(al == '1' and bo == '1'): c.append(int(t)) elif(al == '1'): a.append(int(t)) elif(bo == '1'): b.append(int(t)) if(len(c)+len(a) < k or len(c)+len(b) < k): print(-1) quit() c.sort() a.sort() b.sort() for i in range(1,len(c)): c[i] = c[i] + c[i-1] for i in range(1,len(a)): a[i] = a[i] + a[i-1] for i in range(1,len(b)): b[i] = b[i] + b[i-1] high = 2147483640 p = 0 tempo = 0 while(p <= len(c) and p<= k): if(p>0): tempo = c[p-1] else: tempo = 0 dif = k-p if(len(a)>= dif and len(b)>=dif): if(dif > 0): tempo = tempo + (a[dif-1]+ b[dif-1]) if(high >= tempo): high = tempo p = p + 1 print(high)
11
PYTHON3
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- n,k=map(int,input().split()) a=list() b=list() c=list() c1=0 c2=0 for i in range (n): a1,a2,a3=map(int,input().split()) if a2==1 and a3==1: c.append(a1) c1+=1 c2+=1 elif a2==1: a.append(a1) c1+=1 elif a3==1: b.append(a1) c2+=1 if c2<k or c1<k: print(-1) else: a.sort() b.sort() for i in range (min(len(a),len(b))): c.append(a[i]+b[i]) c.sort() r=0 for i in range (k): r+=c[i] print(r)
11
PYTHON3
n,k = [int(x) for x in input().split()] bookA = [] bookB = [] bookC = [] for i in range(n): a,b,c = [int(x) for x in input().split()] if b == c == 1: bookC.append((a,b,c)) if b == 1 != c: bookA.append((a,b,c)) if c == 1 != b: bookB.append((a,b,c)) bookA.sort(key = lambda x : x[0], reverse = True) bookB.sort(key = lambda x : x[0], reverse = True) bookC.sort(key = lambda x : x[0], reverse = True) totalTime = 0 totalLikes = 0 while (True): if totalLikes >= k: break if len(bookA) == len(bookC) == len(bookB) == 0: break elif (len(bookC) > 0) and (len(bookA) == 0 or len(bookB) == 0 or bookC[len(bookC) - 1][0] <= bookA[len(bookA) - 1][0] + bookB[len(bookB) - 1][0]): totalTime += bookC[len(bookC) - 1][0] bookC.pop() totalLikes += 1 elif len(bookA) > 0 and len(bookB) > 0: totalTime += bookA[len(bookA) - 1][0] + bookB[len(bookB) - 1][0] totalLikes += 1 bookA.pop() bookB.pop() else: break if totalLikes >= k: print(totalTime) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3fll; const int N = 1e4 + 10; const int M = 3e6 + 10; const int maxn = 1e6 + 10; const int mod = 1000173169; const double eps = 1e-10; const double pi = acos(-1.0); struct Tree { int num[N << 2], sum[N << 2]; void add(int rt, int l, int r, int p) { num[rt]++; sum[rt] += p; if (l == r) return; int mid = ((l + r) >> 1); if (p <= mid) add(rt << 1, l, mid, p); else add(rt << 1 | 1, mid + 1, r, p); } int getPos(int rt, int l, int r, int& val) { if (l == r) return l; int mid = ((l + r) >> 1); if (num[rt << 1] >= val) return getPos(rt << 1, l, mid, val); else { val -= num[rt << 1]; return getPos(rt << 1 | 1, mid + 1, r, val); } } int getSum(int rt, int l, int r, int pos) { if (r <= pos) return sum[rt]; int mid = ((l + r) >> 1); int res = 0; if (l <= pos) res = getSum(rt << 1, l, mid, pos); if (mid < pos) res += getSum(rt << 1 | 1, mid + 1, r, pos); return res; } } seg; int n, m, k; vector<int> id; vector<pair<int, int> > a[3], b, p, res; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m >> k; int mx = 1e4; for (int i = 1; i <= n; i++) { int t, x, y; cin >> t >> x >> y; x = x << 1 | y; if (x == 3) b.emplace_back(t, i); else if (x) a[x].emplace_back(t, i); else { seg.add(1, 1, mx, t); res.emplace_back(t, i); } } sort(a[1].begin(), a[1].end()); sort(a[2].begin(), a[2].end()); sort(b.begin(), b.end()); int cnt1 = 0, cnt2 = 0; int t1 = min(min(((int)a[1].size()), ((int)a[2].size())), k); int cur = 0; for (int i = 0; i < t1; i++) { cur += a[1][i].first + a[2][i].first; p.emplace_back(a[1][i].first, a[2][i].first); cnt1++; cnt2 += 2; } for (int i = t1; i < max(((int)a[1].size()), ((int)a[2].size())); i++) { if (i < ((int)a[1].size())) seg.add(1, 1, mx, a[1][i].first), res.push_back(a[1][i]); if (i < ((int)a[2].size())) seg.add(1, 1, mx, a[2][i].first), res.push_back(a[2][i]); } for (int i = k; i < ((int)b.size()); i++) { seg.add(1, 1, mx, b[i].first); res.push_back(b[i]); } int P = -1; long long ans = INF; int t2 = min(((int)b.size()), k); for (int i = 0; i <= t2; i++) { if (cnt1 == k && cnt2 <= m) { long long res = INF; if (cnt2 == m) res = cur; else if (cnt2 + seg.num[1] >= m) { int val = m - cnt2; int pos = seg.getPos(1, 1, mx, val); res = pos * val + cur; if (pos > 1) res += seg.getSum(1, 1, mx, pos - 1); } if (ans > res) { ans = res; P = i; } } if (i < t2) { if (cnt1 < k) { cur += b[i].first; cnt1++; cnt2++; } else if (!p.empty()) { pair<int, int> t = p.back(); p.pop_back(); cur -= t.first + t.second; seg.add(1, 1, mx, t.first); seg.add(1, 1, mx, t.second); cur += b[i].first; cnt2--; } } } if (ans == INF) cout << "-1\n"; else { cout << ans << '\n'; for (int i = 0; i < P; i++) id.push_back(b[i].second); for (int i = 0; i < t1; i++) { if (P + i + 1 <= k) { id.push_back(a[1][i].second); id.push_back(a[2][i].second); } else { res.push_back(a[1][i]); res.push_back(a[2][i]); } } sort(res.begin(), res.end()); for (int i = 0; i < ((int)res.size()); i++) { if (((int)id.size()) == m) break; id.push_back(res[i].second); } for (int v : id) cout << v << ' '; cout << '\n'; assert(((int)id.size()) == m); } return 0; }
11
CPP
n,k = map(int, input().split()) alice = list() bob = list() common = list() for _ in range (n): t,a,b = map(int, input().split()) if a == 1 and b == 1: common.append (t) elif a == 1: alice.append (t) elif b == 1: bob.append (t) if len(common) + len(alice) < k: ans = -1 elif len(common) + len(bob) < k: ans = -1 else: common.sort() alice.sort() bob.sort() commonP = [0]*len(common) aliceP = [0]*len(alice) bobP = [0]*len(bob) if len(common) > 0: commonP[0] = common[0] for i in range (1, len(commonP)): commonP[i] = commonP[i-1] + common[i] if len(alice) > 0: aliceP[0] = alice[0] for i in range (1, len(alice)): aliceP[i] = aliceP[i-1] + alice[i] if len(bob) > 0: bobP[0] = bob[0] for i in range (1, len(bob)): bobP[i] = bobP[i-1] + bob[i] # print (common, commonP) # print (alice, aliceP) # print (bob, bobP) if len(common) == 0: ans = aliceP[k-1] + bobP[k-1] else: ans = None for i in range (0, len(common)+1): if i > k: break if i == k: choice = commonP[k-1] else: if len(alice)<(k-i) or len(bob)<(k-i): continue if i ==0: choice = 0 else: choice = commonP[i-1] try: choice += aliceP[k-i-1] except: pass try: choice += bobP[k-i-1] except: pass # print (i, choice) if ans == 0: continue if ans is None: ans = choice else: ans = min (ans, choice) print (ans)
11
PYTHON3
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization("unroll-loops") using namespace std; long long dx[] = {1, 0, -1, 0}; long long dy[] = {0, 1, 0, -1}; void __print(long x) { cerr << x; } void __print(long long x) { cerr << x; } void __print(unsigned x) { cerr << x; } void __print(unsigned long x) { cerr << x; } void __print(unsigned long long x) { cerr << x; } void __print(float x) { cerr << x; } void __print(double x) { cerr << x; } void __print(long double x) { cerr << x; } void __print(char x) { cerr << '\'' << x << '\''; } void __print(const char *x) { cerr << '\"' << x << '\"'; } void __print(const string &x) { cerr << '\"' << x << '\"'; } void __print(bool x) { cerr << (x ? "true" : "false"); } template <typename T, typename V> void __print(const pair<T, V> &x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; } template <typename T> void __print(const T &x) { long long f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; } void _print() { cerr << "]\n"; } template <typename T, typename... V> void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); } long long solve() { long long n, k; cin >> n >> k; vector<pair<long long, pair<long long, long long>>> v; long long alice = 0, bob = 0, ans = 0; multiset<long long> both, al, bo; for (long long i = 0; i < n; i++) { long long time, a, b; cin >> time >> a >> b; if (a && !b) al.insert(time); if (!a && b) bo.insert(time); else if (a && b) both.insert(time); v.push_back({time, {a, b}}); if (a == 1) alice++; if (b == 1) bob++; } if (alice < k || bob < k) return -1; while (al.size() && bo.size() && both.size() && k) { long long ali = *al.begin(); long long bobi = *bo.begin(); long long bot = *both.begin(); if (ali + bobi < bot) { al.erase(al.find(ali)); bo.erase(bo.find(bobi)); ans += ali + bobi; } else { both.erase(both.find(bot)); ans += bot; } k--; } while (k && al.size() && bo.size()) { k--; long long ali = *al.begin(); long long bobi = *bo.begin(); al.erase(al.find(ali)); bo.erase(bo.find(bobi)); ans += ali + bobi; } while (k && both.size()) { k--; long long bot = *both.begin(); both.erase(both.find(bot)); ans += bot; } return ans; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout << solve(); return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; const int INF = 2e9 + 1; int n, m, k, p1, p2, sum = 0, sumSmall = 0, minVal = INF; pair<int, int> rs; vector<pair<int, int> > a[2][2]; set<pair<int, int> > small, large; void updateSmall(pair<int, int> val, int type) { if (type == 0) { small.insert(val); sumSmall += val.first; } else { small.erase(small.find(val)); sumSmall -= val.first; } } void balance() { while (small.size() > m - p1 - 2 * p2 - 3) { large.insert(*small.rbegin()); updateSmall(*small.rbegin(), 1); } while (small.size() < m - p1 - 2 * p2 - 3) { updateSmall(*large.begin(), 0); large.erase(large.begin()); } while (small.size() > 0 && large.size() > 0) { pair<int, int> p1 = *small.rbegin(); pair<int, int> p2 = *large.begin(); if (p1.first <= p2.first) break; updateSmall(p1, 1); large.erase(large.find(p2)); updateSmall(p2, 0); large.insert(p1); } } void init() { p1 = min((int)a[1][1].size(), k) - 1, p2 = max(k - (int)a[1][1].size(), 0) - 1; for (int i = 0; i <= p1; i++) sum += a[1][1][i].first; for (int i = 0; i <= p2; i++) sum += a[0][1][i].first + a[1][0][i].first; for (int i = p1 + 1; i < a[1][1].size(); i++) updateSmall(a[1][1][i], 0); for (int i = p2 + 1; i < a[0][1].size(); i++) updateSmall(a[0][1][i], 0); for (int i = p2 + 1; i < a[1][0].size(); i++) updateSmall(a[1][0][i], 0); for (int i = 0; i < a[0][0].size(); i++) updateSmall(a[0][0][i], 0); balance(); minVal = sum + sumSmall; rs = pair<int, int>(p1, p2); } void process() { while (p1 >= 0) { updateSmall(a[1][1][p1], 0); sum -= a[1][1][p1--].first; p2++; if (p2 >= min(a[0][1].size(), a[1][0].size())) return; if (m - p1 - 2 * p2 - 3 < 0) return; sum += a[0][1][p2].first + a[1][0][p2].first; if (small.find(a[0][1][p2]) != small.end()) updateSmall(a[0][1][p2], 1); else large.erase(large.find(a[0][1][p2])); if (small.find(a[1][0][p2]) != small.end()) updateSmall(a[1][0][p2], 1); else large.erase(large.find(a[1][0][p2])); balance(); if (minVal > sum + sumSmall) { minVal = sum + sumSmall; rs = pair<int, int>(p1, p2); } } } void print() { cout << minVal << '\n'; for (int i = 0; i <= rs.first; i++) cout << a[1][1][i].second << ' '; for (int i = 0; i <= rs.second; i++) cout << a[0][1][i].second << ' ' << a[1][0][i].second << ' '; vector<pair<int, int> > comb; for (int i = 0; i < a[0][0].size(); i++) comb.push_back(a[0][0][i]); for (int i = rs.first + 1; i < a[1][1].size(); i++) comb.push_back(a[1][1][i]); for (int i = rs.second + 1; i < a[0][1].size(); i++) comb.push_back(a[0][1][i]); for (int i = rs.second + 1; i < a[1][0].size(); i++) comb.push_back(a[1][0][i]); sort(comb.begin(), comb.end()); int rem = m - rs.first - 2 * rs.second - 3; for (int i = 0; i < rem; i++) cout << comb[i].second << ' '; } int main() { cin >> n >> m >> k; int t, x, y; for (int i = 1; i <= n; i++) { cin >> t >> x >> y; a[x][y].push_back(pair<int, int>(t, i)); } for (int i = 0; i <= 1; i++) for (int j = 0; j <= 1; j++) sort(a[i][j].begin(), a[i][j].end()); if (a[1][1].size() + min(a[1][0].size(), a[0][1].size()) < k || min((int)a[1][1].size(), m) + 2 * max(k - (int)a[1][1].size(), 0) > m) { cout << -1; return 0; } init(); process(); print(); }
11
CPP
import sys input = sys.stdin.readline def main(): n, k = map(int, input().split()) a = [] b = [] whole = [] for _ in range(n): t, x, y = map(int, input().split()) if x + y == 2: whole.append(t) elif x + y == 1: if x: a.append(t) else: b.append(t) a.sort() b.sort() for x, y in zip(a, b): whole.append(x + y) whole.sort() if len(whole) < k: print('-1') else: print(sum(whole[:k])) main()
11
PYTHON3
from sys import stdin inp = lambda : stdin.readline().strip() n, k = [int(x) for x in inp().split()] b = [] for _ in range(n): b.append([int(x) for x in inp().split()]) both = [] alice = [] bob = [] for i in b: if i[1] == 1 and i[2] == 1: both.append(i[:]) elif i[1] == 1: alice.append(i[:]) elif i[2] == 1: bob.append(i[:]) if len(alice)+len(both) < k or len(bob) + len(both) <k: print(-1) exit() both.sort(key = lambda x:x[0]) alice.sort(key = lambda x:x[0]) bob.sort(key = lambda x:x[0]) b = 0 a = 0 bb = 0 cost = 0 liked = 0 minimum = min(len(alice),len(bob)) x = max(k-minimum,0) for i in range(x): if liked == k: print(cost) exit() cost += both[i][0] b += 1 liked += 1 while True: if liked == k: print(cost) break if b < len(both) and a<len(alice) and bb<len(bob) and both[b][0] <= alice[a][0] + bob[bb][0]: cost += both[b][0] b += 1 liked += 1 else: cost += alice[a][0] + bob[bb][0] bb += 1 a += 1 liked += 1
11
PYTHON3
import sys input = sys.stdin.readline n, k = map(int, input().split()) a, b, ab = [], [], [] prea, preb, preab = [0], [0], [0] ans = [] for _ in range(n): t1, t2, t3 = map(int, input().split()) if t2 == t3 == 1: ab.append(t1) elif t2 == 1: a.append(t1) elif t3 == 1: b.append(t1) ab.sort() a.sort() b.sort() na, nb, nab = len(a), len(b), len(ab) if nab + min(na, nb) < k: print(-1) sys.exit() if na: for x in a: prea.append(prea[-1] + x) if nb: for x in b: preb.append(preb[-1] + x) if nab: for x in ab: preab.append(preab[-1] + x) if na == 0 or nb == 0: if k <= nab: print(preab[k]) else: print(-1) else: for x in range(k + 1): if nab >= x and na >= k - x and nb >= k - x: ans.append(preab[x] + prea[k - x] + preb[k - x]) if len(ans) == 0: print(-1) else: print(min(ans))
11
PYTHON3
n, k = map(int, input().split()) alice = [] bob = [] both = [] for i in range(n): t, a, b = map(int, input().split()) if a == b == 0: continue if a == b == 1: both.append(t) elif a == 1 and b == 0: alice.append(t) elif a == 0 and b == 1: bob.append(t) alice.sort() bob.sort() for i in range(min(len(alice), len(bob))): both.append(alice[i] + bob[i]) if len(both) < k: print(-1) else: both.sort() ans = 0 for i in range(k): ans += both[i] print(ans)
11
PYTHON3
def reading(numb,mass,c1,c2): if c1<numb or c2<numb : return -1 true_mass1=[] true_mass2=[] true_mass3=[] for i in mass: if i[1]!=0 or i[2]!=0: if i[1]==0: true_mass1.append(i) elif i[2]==0: true_mass2.append(i) else: true_mass3.append(i) true_mass1.sort(key = lambda p:p[0]) true_mass2.sort(key=lambda p: p[0]) true_mass3.sort(key=lambda p: p[0]) #print(true_mass3) i=0 j=0 k=0 deltai=len(true_mass3) deltaj=len(true_mass2) deltak=len(true_mass1) result=0 for d in range(numb): if deltai!=i and deltaj!=j and deltak!=k: if true_mass3[i][0]<=true_mass2[j][0]+true_mass1[k][0]: result+=true_mass3[i][0] i+=1 else: result += true_mass2[j][0] + true_mass1[k][0] k += 1 j += 1 elif deltai==i: result += true_mass2[j][0] + true_mass1[k][0] k+=1 j+=1 elif deltaj==j or deltak==k: result += true_mass3[i][0] i += 1 return result t=[int(i) for i in input().strip().split()] n=t[1] count1=0 count2=0 mass=[] for i in range(t[0]): string=[int(j) for j in input().strip().split()] mass.append(string) if string[1]==1: count1+=1 if string[2]==1: count2+=1 print(reading(n,mass,count1,count2))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; vector<int> t(n), a(n), b(n); int cnt1 = 0, cnt2 = 0; int cnt3 = 0; priority_queue<int, vector<int>, greater<int> > pqboth; for (int i = 0; i < n; i++) { cin >> t[i] >> a[i] >> b[i]; if (a[i] != 0 || b[i] != 0) pq.push({t[i], i}); if (a[i] == 1 && b[i] == 1) { pqboth.push(t[i]); cnt3++; } if (a[i] == 1) cnt1++; if (b[i] == 1) cnt2++; } if (cnt1 < k || cnt2 < k) { cout << "-1\n"; return; } cnt1 = 0, cnt2 = 0; long long int time = 0; priority_queue<int> pq3, pq4; int cnt4 = 0; while (!pq.empty() && (cnt1 < k || cnt2 < k)) { int x = pq.top().first; int y = pq.top().second; time += (long long int)x; if (a[y] == 1 && b[y] == 1) cnt4++; if (a[y] == 1) cnt1++; if (b[y] == 1) cnt2++; if (a[y] == 1 && b[y] == 0) { pq3.push(x); } if (a[y] == 0 && b[y] == 1) { pq4.push(x); } pq.pop(); } while (cnt4 > 0 && !pqboth.empty()) { cnt4--; pqboth.pop(); } while (cnt1 > k && !pq3.empty()) { cnt1--; time -= (long long int)pq3.top(); pq3.pop(); } while (cnt2 > k && !pq4.empty()) { cnt2--; time -= (long long int)pq4.top(); pq4.pop(); } while (!pqboth.empty() && !pq3.empty() && !pq4.empty()) { int x = pqboth.top(); int y = pq3.top(); int z = pq4.top(); if (x < y + z) time += (long long int)(x - y - z); else break; pqboth.pop(); pq3.pop(); pq4.pop(); } cout << time << "\n"; } int main() { solve(); return 0; }
11
CPP
n,k = [int(x) for x in input().split()] res = 0 pick =0 both = [] alice = [] bob = [] for i in range(n): t,a,b=[int(x) for x in input().split()] if a == 1 and b ==1: both.append(t) elif a == 1 and b == 0: alice.append(t) elif a == 0 and b == 1: bob.append(t) alice.sort() bob.sort() both.sort() n1,n2,n3 = len(both),len(alice),len(bob) i,j,l = 0, 0, 0 while i < n1 and j < n2 and l < n3: if both[i] <= alice[j] + bob[l]: res += both[i] i += 1 pick += 1 if pick == k: break else: res += alice[j] + bob[l] j += 1 l += 1 pick += 1 if pick == k: break if (j >= n2 or l >= n3): while i < n1: res += both[i] i += 1 pick += 1 if pick == k: break elif (i >= n1): while j < n2 and l < n3: res += alice[j] + bob[l] j += 1 l += 1 pick += 1 if pick == k: break if pick == k: print(res) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; struct cmp { bool operator()(const long long &a, const long long &b) { return a >= b; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long n, k; cin >> n >> k; long long first = 0, second = 0, ans = 0; long long temp1 = 0, temp2 = 0, temp3 = 0; priority_queue<long long, vector<long long>, cmp> a; priority_queue<long long, vector<long long>, cmp> b; priority_queue<long long, vector<long long>, cmp> c; for (int i = 0; i < n; i++) { cin >> temp1 >> temp2 >> temp3; if (temp2 != 0 && temp3 == 0) a.push(temp1); else if (temp2 == 0 && temp3 != 0) b.push(temp1); else if (temp2 == 1 && temp3 == 1) c.push(temp1); } if (a.size() + c.size() < k || b.size() + c.size() < k) { cout << -1; return 0; } long long ran = min(a.size(), b.size()); while (ran--) { c.push(a.top() + b.top()); a.pop(); b.pop(); } while (k--) { ans += c.top(); c.pop(); } cout << ans; return 0; }
11
CPP
# not necessary to use a heap but hey why not, I needed a refresher from heapq import * n, k = [int(x) for x in input().split()] alice = [] bob = [] both = [] for _ in range(n): t, a, b = [int(x) for x in input().split()] if a and b: heappush(both, t) elif a: heappush(alice, t) elif b: heappush(bob, t) while len(alice) and len(bob): heappush(both, heappop(alice) + heappop(bob)) if len(both) < k: print(-1) else: time = 0 for _ in range(k): time += heappop(both) print(time)
11
PYTHON3
from sys import stdin n,k = list(map(int, stdin.readline().strip().split(' '))) AB = [] A = [] B = [] for i in range(n): t,a,b = list(map(int, stdin.readline().strip().split(' '))) if a == 1 and b == 1: AB.append(t) elif a == 1: A.append(t) elif b == 1: B.append(t) AB.sort() A.sort() B.sort() ans = 0 abi = 0 ai = 0 bi = 0 isPossible = True for i in range(k): if abi == len(AB) and (ai == len(A) or bi == len(B)): isPossible = False break if abi == len(AB): ans += (A[ai] + B[bi]) ai += 1 bi += 1 continue if ai == len(A) or bi == len(B): ans += AB[abi] abi += 1 continue if A[ai] + B[bi] <= AB[abi]: ans += (A[ai] + B[bi]) ai += 1 bi += 1 continue ans += AB[abi] abi += 1 continue if isPossible: print(ans) else: print(-1)
11
PYTHON3
k, n = [int(i) for i in input().split()] a = [] b = [] both = [] for _ in range(k): t,x,y = [int(i) for i in input().split()] if(x == 1 and y == 1): both.append(t) elif x == 1: a.append(t) elif y == 1: b.append(t) a.sort() b.sort() both.sort() # print(a,b,both) if len(a) + len(both) < n or len(b) + len(both) < n: print(-1) quit() bI = 0 aI = 0 bothI = 0 count = 0 t = 0 while count < n: count += 1 if len(a) != aI and len(b) != bI and len(both) != bothI: if a[aI]+b[bI]<both[bothI]: t += a[aI]+b[bI] aI += 1 bI += 1 else: t += both[bothI] bothI += 1 elif len(a) != aI and len(b) != bI: #both is empty t += a[aI]+b[bI] aI += 1 bI += 1 else: t += both[bothI] bothI += 1 print(t)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int mod = 1000000007; const int inf = 1034567891; const long long LL_INF = 1234567890123456789ll; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cout << name << " : " << arg1 << '\n'; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cout.write(names, comma - names) << " : " << arg1 << " | "; __f(comma + 1, args...); } template <typename T> T GCD(T a, T b) { long long t; while (a) { t = a; a = b % a; b = t; } return b; } template <typename T> string toString(T a) { return to_string(a); } template <typename T> void toInt(string s, T& x) { stringstream str(s); str >> x; } inline int add(int x, int y) { x += y; if (x >= mod) x -= mod; return x; } inline int sub(int x, int y) { x -= y; if (x < 0) x += mod; return x; } inline int mul(int x, int y) { return (x * 1ll * y) % mod; } inline int powr(int a, long long b) { int x = 1 % mod; while (b) { if (b & 1) x = mul(x, a); a = mul(a, a); b >>= 1; } return x; } inline int inv(int a) { return powr(a, mod - 2); } const int N = 2e5 + 5; int tt[N], aa[N], bb[N]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m, k; cin >> n >> m >> k; vector<pair<long long, long long> > vec[4]; for (int i = 0; i < 4; i++) vec[i].push_back({0, 0}); for (int i = 0; i < n; i++) { cin >> tt[i] >> aa[i] >> bb[i]; int x = aa[i] * 2 + bb[i]; vec[x].push_back({tt[i], i + 1}); } int a = vec[2].size() - 1, b = vec[1].size() - 1, ab = vec[3].size() - 1, d = vec[0].size() - 1; if (a + ab < k || b + ab < k) { cout << -1 << '\n'; return 0; } for (int i = 0; i < 4; i++) { sort(vec[i].begin(), vec[i].end()); } for (int i = 1; i <= a; i++) { vec[2][i].first += vec[2][i - 1].first; } for (int i = 1; i <= b; i++) { vec[1][i].first += vec[1][i - 1].first; } for (int i = 1; i <= ab; i++) { vec[3][i].first += vec[3][i - 1].first; } set<pair<long long, long long> > s; for (int i = 1; i <= d; i++) { s.insert({vec[0][i].first, vec[0][i].second}); } for (int i = 1; i <= ab; i++) { s.insert({vec[3][i].first - vec[3][i - 1].first, vec[3][i].second}); } long long sum = 0; for (auto it : s) { sum += it.first; } long long ans = LL_INF, pos = 0, p1 = 0, p2 = 0; int id1 = a, id2 = b; set<pair<long long, long long> > temp; bool first = false; set<pair<long long, long long> > ready; for (int i = 0; i <= ab; i++) { int x = k - i; int y = m - i - 2 * x; if (i) { auto it = make_pair(vec[3][i].first - vec[3][i - 1].first, vec[3][i].second); ready.erase(it); if (s.count(it)) { sum -= it.first; s.erase(it); } } if (y < 0 || x < 0 || x > min(a, b)) continue; if (!first) { for (int j = x + 1; j <= a; j++) { sum += vec[2][j].first - vec[2][j - 1].first; s.insert({vec[2][j].first - vec[2][j - 1].first, vec[2][j].second}); } for (int j = x + 1; j <= b; j++) { sum += vec[1][j].first - vec[1][j - 1].first; s.insert({vec[1][j].first - vec[1][j - 1].first, vec[1][j].second}); } } first = true; while (s.size() && s.size() > y) { ready.insert(*s.rbegin()); sum -= (*s.rbegin()).first; s.erase(*s.rbegin()); } while (ready.size() && s.size() < y) { auto it = *ready.begin(); sum += it.first; s.insert(it); ready.erase(it); } while (ready.size() && s.size() && (*ready.begin()).first < (*s.rbegin()).first) { auto it1 = *ready.begin(); auto it2 = *s.rbegin(); sum -= it2.first; sum += it1.first; s.erase(it2); ready.erase(it1); s.insert(it1); ready.insert(it2); } long long cur = vec[3][i].first + vec[2][x].first + vec[1][x].first + sum; if (s.size() == y) { if (cur < ans) { ans = cur; pos = i; p1 = x; p2 = x; } } if (x > 0 && x <= a) { sum += vec[2][x].first - vec[2][x - 1].first; s.insert({vec[2][x].first - vec[2][x - 1].first, vec[2][x].second}); } if (x > 0 && x <= b) { sum += vec[1][x].first - vec[1][x - 1].first; s.insert({vec[1][x].first - vec[1][x - 1].first, vec[1][x].second}); } } if (ans == LL_INF) { cout << -1 << '\n'; return 0; } cout << ans << '\n'; for (int i = 1; i <= pos; i++) { cout << vec[3][i].second << " "; } for (int i = 1; i <= p2; i++) { cout << vec[1][i].second << " "; } for (int i = 1; i <= p1; i++) { cout << vec[2][i].second << " "; } s.clear(); ready.clear(); for (int i = 1; i <= d; i++) { s.insert({vec[0][i].first, vec[0][i].second}); } for (int i = 1; i <= ab; i++) { s.insert({vec[3][i].first - vec[3][i - 1].first, vec[3][i].second}); } sum = 0; for (auto it : s) { sum += it.first; } first = false; for (int i = 0; i <= ab; i++) { int x = k - i; int y = m - i - 2 * x; if (i) { auto it = make_pair(vec[3][i].first - vec[3][i - 1].first, vec[3][i].second); ready.erase(it); if (s.count(it)) { sum -= it.first; s.erase(it); } } if (y < 0 || x < 0 || x > min(a, b)) continue; if (!first) { for (int j = x + 1; j <= a; j++) { sum += vec[2][j].first - vec[2][j - 1].first; s.insert({vec[2][j].first - vec[2][j - 1].first, vec[2][j].second}); } for (int j = x + 1; j <= b; j++) { sum += vec[1][j].first - vec[1][j - 1].first; s.insert({vec[1][j].first - vec[1][j - 1].first, vec[1][j].second}); } } first = true; while (s.size() && s.size() > y) { ready.insert(*s.rbegin()); sum -= (*s.rbegin()).first; s.erase(*s.rbegin()); } while (ready.size() && s.size() < y) { auto it = *ready.begin(); sum += it.first; s.insert(it); ready.erase(it); } while (ready.size() && s.size() && (*ready.begin()).first < (*s.rbegin()).first) { auto it1 = *ready.begin(); auto it2 = *s.rbegin(); sum -= it2.first; sum += it1.first; s.erase(it2); ready.erase(it1); s.insert(it1); ready.insert(it2); } long long cur = vec[3][i].first + vec[2][x].first + vec[1][x].first + sum; if (i == pos) { for (auto it : s) { cout << it.second << " "; } cout << '\n'; return 0; } if (x > 0 && x <= a) { sum += vec[2][x].first - vec[2][x - 1].first; s.insert({vec[2][x].first - vec[2][x - 1].first, vec[2][x].second}); } if (x > 0 && x <= b) { sum += vec[1][x].first - vec[1][x - 1].first; s.insert({vec[1][x].first - vec[1][x - 1].first, vec[1][x].second}); } } cout << '\n'; return 0; }
11
CPP
import bisect def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) ])) def invr(): return(map(int,input().split())) l = inlt() n = l[0] k = l[1] alice = [] bob = [] good = [] for i in range(n): l = inlt() if(l[1] == 1 and l[2] == 1): good.append(l) elif(l[1] == 1): alice.append(l) elif(l[2] == 1): bob.append(l) good.sort(key = lambda j:j[0]) alice.sort(key = lambda j:j[0]) bob.sort(key = lambda j:j[0]) a = 0 b = 0 g = 0 total = 0 book = 0 while(book < k): if(g < len(good)): if(a >= len(alice) or b >= len(bob)): total += good[g][0] g += 1 else: if(alice[a][0] + bob[b][0] < good[g][0]): total += alice[a][0] + bob[b][0] a += 1 b += 1 else: total += good[g][0] g += 1 elif(a < len(alice) and b < len(bob)): total += alice[a][0] + bob[b][0] a += 1 b += 1 else: total = -1 break book += 1 print(total)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, k; cin >> n >> k; vector<vector<long long>> b(4, vector<long long>(1, 0LL)); for (int i = 0; i < n; i++) { long long t, x, y; cin >> t >> x >> y; b[x * 2 + y].push_back(t); } for (int i = 1; i < 4; i++) { sort(b[i].begin(), b[i].end()); long long acc = 0LL; for (auto &j : b[i]) { long long x = j; j += acc; acc += x; } } long long ans = (k < (int)b[1].size() && k < (int)b[2].size()) ? b[1][k] + b[2][k] : LONG_LONG_MAX; for (int i = 1; i < (int)b[3].size() && k - i >= 0; i++) { if (k - i == 0) ans = min(ans, b[3][i]); else if (k - i > 0) { if (k - i > (int)b[1].size() - 1 || k - i > (int)b[2].size() - 1) continue; else ans = min(ans, b[3][i] + b[1][k - i] + b[2][k - i]); } } if (ans == LONG_LONG_MAX) cout << -1 << "\n"; else cout << ans << "\n"; }
11
CPP
n,k=map(int,input().split()) time=[] a=[] b=[] count_a=0 count_b=0 for i in range(n): t,a1,b1=map(int,input().split()) time.append(t) a.append(a1) b.append(b1) if a1==1: count_a+=1 if b1==1: count_b+=1 #print(count_a,count_b) if count_a<k or count_b<k: print(-1) else: both=[] a_not_b=[] b_not_a=[] for i in range(n): if a[i]==1 and b[i]==1: both.append(time[i]) elif a[i]==1 and b[i]==0: a_not_b.append(time[i]) elif a[i]==0 and b[i]==1: b_not_a.append(time[i]) #print(both,a_not_b,b_not_a) a_not_b.sort() b_not_a.sort() both_len=len(both) a_not_b_len=len(a_not_b) b_not_a_len=len(b_not_a) final=[] req_len=min(a_not_b_len,b_not_a_len) for i in range(req_len): final.append(a_not_b[i]+b_not_a[i]) #print(both,final) final.extend(both) final.sort() if len(final)<k: print(-1) else: ans=0 for i in range(k): ans+=final[i] #print(final) print(ans)
11
PYTHON3
line = input() n, k = [int(i) for i in line.split(' ')] allL, aliceL, bobL = [], [], [] for i in range(n): line = input() t, a, b = [int(j) for j in line.split(' ')] if a == 1 and b == 1: allL.append(t) elif a == 1: aliceL.append(t) elif b == 1: bobL.append(t) allL.sort() aliceL.sort() bobL.sort() # print(allL) # print(aliceL) # print(bobL) if len(allL) + min(len(aliceL), len(bobL)) < k: print(-1) else: x = min(len(allL), k) b = k - x res = sum(allL[:x]) + sum(aliceL[:b]) + sum(bobL[:b]) while x > 0 and b < min(len(aliceL), len(bobL)): x -= 1 if res <= res - allL[x] + aliceL[b] + bobL[b]: break else: res = res - allL[x] + aliceL[b] + bobL[b] b += 1 print(res)
11
PYTHON3
#!/usr/bin/env python3 import io import os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def get_str(): return input().decode().strip() def rint(): return map(int, input().split()) def oint(): return int(input()) n, k = rint() tab = [] for i in range(n): tab.append(tuple(rint())) tab.sort() ai = [] bi = [] bc = 0 tot_time = 0 ka = 0 kb = 0 for i in range(n): t, a, b = tab[i] if a and not b: if ka < k: ka += 1 ai.append(i) tot_time += t elif b and not a: if kb < k: kb += 1 bi.append(i) tot_time += t elif a and b: if ka < k or kb < k: ka += 1 kb += 1 tot_time += t if ka > k: if len(ai): ta = tab[ai.pop()][0] tot_time -= ta ka -= 1 if kb > k: if len(bi): tb = tab[bi.pop()][0] tot_time -= tb kb -= 1 elif ka >= k and kb >= k: if len(ai) and len(bi): ta = tab[ai.pop()][0] tb = tab[bi.pop()][0] if t < ta + tb: tot_time = tot_time - ta - tb + t if ka >= k and kb >= k: print(tot_time) else: print(-1)
11
PYTHON3
import sys from collections import defaultdict as dd from collections import Counter as cc from queue import Queue import math import itertools try: sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass input = lambda: sys.stdin.buffer.readline().rstrip() q,w=map(int,input().split()) e=[] r=[] t=[] z=0 x=0 for i in range(q): a,b,c=map(int,input().split()) if b==1 and c==1: e.append(a) z+=1 x+=1 elif b==1 and c==0: r.append(a) x+=1 elif b==0 and c==1: t.append(a) z+=q r=sorted(r) t=sorted(t) for i in range(min(len(r),len(t))): e.append(r[i]+t[i]) e=sorted(e) i=0 t=0 k=0 b=len(e) if b<w: print(-1) else: while i<w: if t<b: k+=e[t] t+=1 i+=1 print(k)
11
PYTHON3
import sys input = sys.stdin.readline def main(): n, k = map(int, input().split()) a_s = [] b_s = [] ab_s = [] for _ in range(n): t, a, b = map(int, input().split()) if a == b == 1: ab_s.append(t) elif a == 1: a_s.append(t) elif b == 1: b_s.append(t) la = len(a_s) lb = len(b_s) lab = len(ab_s) if la + lab < k or lb + lab < k: print(-1) return a_s.sort() b_s.sort() for i in range(min(la, lb)): tmp = a_s[i] + b_s[i] ab_s.append(tmp) ab_s.sort() print(sum(ab_s[:k])) main() """ for _ in range(int(input())): main() """
11
PYTHON3
n,k=map(int,input().split()) L1=[] L2=[] L3=[] for i in range(n): t, a, b = map(int, input().split()) if a==1 and b==1: L1.append(t) elif a==1 and b==0: L2.append(t) elif a==0 and b==1: L3.append(t) L3.sort() L2.sort() for i in range(min(len(L2), len(L3))): L1.append(L2[i]+L3[i]) if k<=len(L1): L1.sort() print(sum(L1[:k])) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; struct book { int val; int index; }; int n, m, k, tim, minTim = 2000000001; int minIndexVal, xIndex[5]; vector<book> x[4]; int xS[5]; vector<int> books; int currNum[4], minNum[4]; bool compareVal(book p1, book p2) { return p1.val < p2.val; } int sizeOfCurrBooks() { int sum = 0; for (int i = 0; i < 4; i++) sum += currNum[i]; return sum; } void removeMost(int l, int r) { int maxIndex = -1, maxVal = -1; for (int i = 0; i < 4; i++) { if (currNum[i] == 0) continue; if ((i == 1 || i == 2) && currNum[i] <= l) continue; if (i == 3 && currNum[i] <= r) continue; if (x[i][currNum[i] - 1].val > maxVal) { maxVal = x[i][currNum[i] - 1].val; maxIndex = i; } } tim -= maxVal; currNum[maxIndex]--; } void addLeast() { int minIndex = -1, minVal = 2000000001; for (int i = 0; i < 4; i++) { if (x[i][currNum[i]].val != 2000000001 && x[i][currNum[i]].val < minVal) { minVal = x[i][currNum[i]].val; minIndex = i; } } tim += minVal; currNum[minIndex]++; } void goToPoss(int l, int r) { if (currNum[3] >= r) { removeMost(l, r); removeMost(l, r); addLeast(); addLeast(); } else { tim += x[3][currNum[3]].val; currNum[3]++; removeMost(l, r); removeMost(l, r); addLeast(); } } int main() { cin >> n >> m >> k; int t, a, b; for (int i = 0; i < n; i++) { cin >> t >> a >> b; x[2 * a + b].push_back({t, i}); } for (int i = 0; i < 4; i++) { sort(x[i].begin(), x[i].end(), compareVal); xS[i] = (int)x[i].size(); x[i].push_back({2000000001, -1}); } xS[4] = min(xS[1], xS[2]); if (xS[3] + xS[4] < k || xS[3] + 2 * (k - xS[3]) > m) cout << -1 << endl; else { currNum[0] = 0; currNum[1] = m - k; currNum[2] = m - k; currNum[3] = 2 * k - m; if (xS[4] < m - k) { currNum[1] = xS[4]; currNum[2] = xS[4]; currNum[3] = k - xS[4]; } while (currNum[3] < 0) { currNum[1]--; currNum[2]--; currNum[3]++; } int left = currNum[1], right = currNum[3]; while (sizeOfCurrBooks() < m) { addLeast(); } tim = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < currNum[i]; j++) tim += x[i][j].val; minTim = tim; for (int i = 0; i < 4; i++) minNum[i] = currNum[i]; while (left > 0 && right < xS[3]) { left--; right++; goToPoss(left, right); if (tim < minTim) { minTim = tim; for (int i = 0; i < 4; i++) minNum[i] = currNum[i]; } } cout << minTim << endl; for (int i = 0; i < 4; i++) for (int j = 0; j < minNum[i]; j++) cout << x[i][j].index + 1 << " "; } }
11
CPP
book_number, like_num = map(int, input().split()) both_like = [] only_alice = [] only_bob = [] for _ in range(book_number): t, a, b = map(int, input().split()) if a == b == 1: both_like.append(t) elif a == 1: only_alice.append(t) elif b == 1: only_bob.append(t) i, j = 0, 0 time = 0 current_like = 0 both_like.sort() only_alice.sort() only_bob.sort() while current_like < like_num: if i < len(both_like) and j < min(len(only_alice), len(only_bob)): if both_like[i] < only_alice[j] + only_bob[j]: time += both_like[i] i += 1 else: time += (only_alice[j] + only_bob[j]) j += 1 current_like += 1 elif i < len(both_like): time += both_like[i] i += 1 current_like +=1 elif j < min(len(only_alice), len(only_bob)): time += (only_alice[j] + only_bob[j]) j += 1 current_like += 1 else: break if current_like == like_num: print(time) else: print(-1)
11
PYTHON3