solution
stringlengths
11
983k
difficulty
int64
0
21
language
stringclasses
2 values
n, k = map(int, input().split()) books = [list(map(int, input().split())) for _ in range(n)] new_books = {str(i // 2) + str(i % 2): [0] for i in range(4)} for book in books: new_books[str(book[1]) + str(book[2])].append(book[0]) for book in new_books.keys(): new_books[book].sort() for i in range(1, len(new_books[book])): new_books[book][i] += new_books[book][i - 1] ans = int(1e18) for taken in range(k + 1): if len(new_books['11']) > taken and len(new_books['10']) > k - taken and len(new_books['01']) > k - taken: ans = min(ans, new_books['11'][taken] + new_books['10'][k - taken] + new_books['01'][k - taken]) print(ans if ans != int(1e18) else -1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const long long INF = 1e18; const long long MAX = 1e5 + 10; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; vector<long long> a, b, ab; ab.push_back(0); a.push_back(0); b.push_back(0); for (int i = 0; i < n; i++) { long long t, A, B; cin >> t >> A >> B; if (A == 1 && B == 1) ab.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()); sort(ab.begin(), ab.end()); long long ans = INF; for (int i = 1; i < ab.size(); i++) ab[i] += ab[i - 1]; for (int i = 1; i < a.size(); i++) a[i] += a[i - 1]; for (int i = 1; i < b.size(); i++) b[i] += b[i - 1]; for (int i = 0; i < min((int)ab.size(), k + 1); i++) { if (a.size() > k - i && b.size() > k - i) ans = min(ans, ab[i] + a[k - i] + b[k - i]); } if (ans != INF) cout << ans << "\n"; else cout << -1 << "\n"; }
11
CPP
#include <bits/stdc++.h> using namespace std; const int MAX = 200005; long long INF = 1e10; vector<long long> books[3]; int type(int a, int b) { if (a && b) return 0; if (a) return 1; return 2; } int main() { ios::sync_with_stdio(0); cin.tie(0); int n, k, t, x, y; cin >> n >> k; for (int i = 0; i < n; i++) { cin >> t >> x >> y; if (!x && !y) continue; books[type(x, y)].push_back(t); } for (int i = 0; i < 3; i++) { sort(books[i].begin(), books[i].end()); for (int j = books[i].size(); j < k; j++) { books[i].push_back(INF); } } long long ans, aux; ans = aux = 0; for (int i = 0; i < k; i++) aux += books[0][i]; ans = aux; for (int i = 0; i < k; i++) { aux -= books[0][k - i - 1]; aux += books[1][i]; aux += books[2][i]; ans = min(aux, ans); } if (ans >= INF) cout << "-1" << '\n'; else cout << ans << '\n'; }
11
CPP
#include <bits/stdc++.h> const int maxn = 2e6 + 1; const int maxm = 1e5 + 10; const long long int mod = 1e9 + 7; const long long int INF = 1e18 + 100; const int inf = 0x3f3f3f3f; const double pi = acos(-1.0); const double eps = 1e-8; using namespace std; multiset<long long int> va, vb, vall; int main() { int n, m; scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) { long long int t; int a, b; scanf("%lld %d %d", &t, &a, &b); if (a == 0 && b == 0) continue; else if (a == 1 && b == 0) va.insert(t); else if (a == 0 && b == 1) vb.insert(t); else vall.insert(t); } long long int ans = 0; while (m--) { if ((int)vall.size() != 0 && (int)va.size() != 0 && (int)vb.size() != 0) { if (*vall.begin() > *va.begin() + *vb.begin()) { ans += *va.begin() + *vb.begin(); va.erase(va.begin()); vb.erase(vb.begin()); } else { ans += *vall.begin(); vall.erase(vall.begin()); } } else if ((int)vall.size() != 0) ans += *vall.begin(), vall.erase(vall.begin()); else if ((int)va.size() != 0 && (int)vb.size() != 0) { ans += *va.begin() + *vb.begin(); va.erase(va.begin()); vb.erase(vb.begin()); } else break; } if (m >= 0) puts("-1"); else printf("%lld\n", ans); }
11
CPP
#include <bits/stdc++.h> using namespace std; int32_t main() { long long int n, k; cin >> n >> k; vector<long long int> v1; vector<long long int> v2; vector<long long int> v; for (long long int i = 0; i < n; i++) { long long int t, a, b; cin >> t >> a >> b; if (a == 1 && b == 1) { v.push_back(t); } else if (a == 0 && b == 1) { v2.push_back(t); } else if (a == 1 && b == 0) { v1.push_back(t); } } if (v1.size() + v.size() < k || v2.size() + v.size() < k) { cout << -1 << "\n"; } else { long long int m1 = v1.size(); long long int m2 = v2.size(); long long int m = v.size(); if (m1 != 0) sort(v1.begin(), v1.end()); if (m2 != 0) sort(v2.begin(), v2.end()); if (m != 0) sort(v.begin(), v.end()); vector<long long int> ans; if (m1 == 0 || m2 == 0) { for (long long int i = 0; i < m; i++) { ans.push_back(v[i]); } } else { long long int p = 0; for (long long int i = 0; i < m1; i++) { if (p < m2) { ans.push_back(v1[i] + v2[p]); p++; } } for (long long int i = 0; i < m; i++) { ans.push_back(v[i]); } } sort(ans.begin(), ans.end()); long long int final = 0; for (long long int i = 0; i < k; i++) { final = final + ans[i]; } cout << final << "\n"; } return 0; }
11
CPP
from collections import deque # for #!/usr/bin/env python import os import sys from io import BytesIO, IOBase # region fastio 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") from bisect import bisect_left as bl from math import log2,ceil from itertools import permutations def main(): # n = int(input()) # l = [int(j) for j in input().split()] # 3 4 240 # 60 90 120 # 80 150 80 150 # for t in range(int(input())): # n = int(input()) n,k =[int(j) for j in input().split()] l = [] for i in range(n): l.append([int(j) for j in input().split()]) l.sort() al = [] bl = [] both = [] for i in range(n): if l[i][1]==1 and l[i][2]==1: both.append(i) elif l[i][1]: al.append(i) elif l[i][2]: bl.append(i) a = 0 b = 0 c = 0 ans = 0 i = k j = k # print(al,bl,both) while(a<len(al) and b<len(bl) and c<len(both) and i>0 and j>0): if l[al[a]][0] <l[both[c]][0] and l[bl[b]][0]<l[both[c]][0] and l[al[a]][0]+ l[bl[b]][0]< l[both[c]][0]: ans+=l[al[a]][0]+ l[bl[b]][0] a+=1 b+=1 else: ans+=l[both[c]][0] c+=1 i-=1 j-=1 # print(i,j,ans,"dsd") if i>0: while(c<len(both) and i>0): ans+=l[both[c]][0] c+=1 i-=1 j-=1 while(a<len(al) and i>0): ans+=l[al[a]][0] a+=1 i-=1 # print(i, ans) if j>0: while(c<len(both) and j>0): ans+=l[both[c]][0] c+=1 j-=1 i-=1 while(b<len(bl) and j>0): ans+=l[bl[b]][0] b+=1 j-=1 if i>0 or j>0: print(-1) else: print(ans) # print(a[0][1]+n*(a[0][0]-1)) # x,y,n =[int(j) for j in input().split()] # a = n//x # if a*x+y<=n: # print(a*x+y) # else: # print((a-1)*x+y) # endregion if __name__ == "__main__": main()
11
PYTHON3
n,k=map(int,input().split()) t10=[] t01=[] t11=[] for x in range(n): t,a,b=map(int,input().split()) if a==0 and b==1: t01.append(t) elif a==1 and b==0: t10.append(t) elif a==1 and b==1: t11.append(t) t10.sort() t01.sort() t11.sort() for x in range(1,len(t01)): t01[x]+=t01[x-1] for x in range(1,len(t10)): t10[x]+=t10[x-1] for x in range(1,len(t11)): t11[x]+=t11[x-1] t10=[0]+t10 t01=[0]+t01 t11=[0]+t11 ans=[] for x in range(len(t11)): if (k-x)>(len(t10)-1) or (k-x)>(len(t01)-1): continue t=0 t+=t11[x] t+=t01[k-x] t+=t10[k-x] ans.append(t) if x==k: break if len(ans)==0: print(-1) else: print(min(ans))
11
PYTHON3
import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,k =I() a=[];b=[] ab=[] for _ in range(n): x,y,z=I() if y and z: ab.append(x) elif y: a.append(x) elif z: b.append(x) a.sort() b.sort() ab.sort() x,y,z=len(a),len(b),len(ab) i=j=l=t=an=0 if x+z <k or y+z<k: print(-1) else: while t!=k: if i>=x or j>=y: an+=ab[l];l+=1 elif l>=z: an+=a[i]+b[j] i+=1;j+=1 else: if a[i]+b[j]<ab[l]: an+=a[i]+b[j] i+=1;j+=1 else: an+=ab[l];l+=1 t+=1 print(an)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const int m_x[] = {-1, 0, 0, 1}; const int m_y[] = {0, -1, 1, 0}; template <typename T, typename S> ostream& operator<<(ostream& output, const pair<T, S>& to_print) { output << to_print.first << ":" << to_print.second; return output; } template <typename T, typename S> ostream& operator<<(ostream& output, const map<T, S>& to_print) { for (typename map<T, S>::const_iterator it = to_print.begin(); it != to_print.end(); it++) output << *it << endl; return output; } template <typename T> ostream& operator<<(ostream& output, const vector<T>& to_print) { for (typename vector<T>::const_iterator it = to_print.begin(); it != to_print.end(); it++) output << *it << " "; return output; } template <typename T> ostream& operator<<(ostream& output, const set<T>& to_print) { for (typename set<T>::const_iterator it = to_print.begin(); it != to_print.end(); it++) output << *it << " "; return output; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, k; cin >> n >> m >> k; set<pair<int, int> > sets[4]; for (int i = 0; i < n; i++) { int t, a, b; cin >> t >> a >> b; if (a == 1 && b == 1) sets[0].insert(make_pair(t, i + 1)); else if (a == 1 && b == 0) sets[1].insert(make_pair(t, i + 1)); else if (a == 0 && b == 1) sets[2].insert(make_pair(t, i + 1)); else sets[3].insert(make_pair(t, i + 1)); } { bool flag_possible = true; int x = sets[0].size(), y = min(sets[1].size(), sets[2].size()); int no_of_likes = x + y; if (no_of_likes < k) flag_possible = false; int m_copy = m - x, k_copy = k - x; if (k_copy > 0) { if (m_copy < 2 * k_copy) flag_possible = false; } if (!flag_possible) { cout << "-1\n"; return 0; } } vector<pair<int, int> > sol, sol2, sol3; int ava = m - k; long long ans = 0; bool flag_cmp = true, flag_cmp2 = true; while (true) { if (k == 0) break; if (sets[1].size() == 0 || sets[2].size() == 0) flag_cmp2 = false; if (sets[0].size() == 0) flag_cmp = false; if (flag_cmp && flag_cmp2 && ava) { pair<int, int> s1 = *sets[0].begin(), s2 = *sets[1].begin(), s3 = *sets[2].begin(); if (s1.first <= s2.first + s3.first) { sets[0].erase(sets[0].begin()); ans += s1.first; k--; m--; sol.push_back(s1); } else if (s1.first > s2.first + s3.first) { sets[1].erase(sets[1].begin()); sets[2].erase(sets[2].begin()); ans += s2.first + s3.first; k--; m -= 2; sol2.push_back(s2); sol2.push_back(s3); ava--; } } else if (flag_cmp) { vector<set<pair<int, int> >::iterator> arr; for (set<pair<int, int> >::iterator it = sets[0].begin(); it != sets[0].end() && k; it++) { sol.push_back(*it); ans += it->first; k--; m--; arr.push_back(it); } for (int i = 0; i < arr.size(); i++) sets[0].erase(arr[i]); break; } else if (flag_cmp2) { vector<set<pair<int, int> >::iterator> arr; for (set<pair<int, int> >::iterator it = sets[1].begin(), it2 = sets[2].begin(); it != sets[1].end() && it2 != sets[2].end() && k; it++, it2++) { sol2.push_back(*it); sol2.push_back(*it2); ans += it->first + it2->first; k--; m -= 2; arr.push_back(it); arr.push_back(it2); } for (int i = 0; i < arr.size(); i++) if (i % 2 == 0) sets[1].erase(arr[i]); else sets[2].erase(arr[i]); break; } } if (m > 0) { set<pair<int, int> >::iterator it[4] = {sets[0].begin(), sets[1].begin(), sets[2].begin(), sets[3].begin()}; while (m--) { vector<pair<pair<int, int>, int> > to_sort; for (int i = 0; i < 4; i++) if (it[i] != sets[i].end()) to_sort.push_back(make_pair(*(it[i]), i)); sort(to_sort.begin(), to_sort.end()); bool flag = false; if (to_sort[0].second == 3 && sol.size() > 0 && it[2] != sets[2].end() && it[1] != sets[1].end()) { pair<int, int> last = *(--sol.end()), cur1 = *it[1], cur2 = *it[2]; if (last.first + to_sort[0].first.first > cur1.first + cur2.first) { sol.erase(--sol.end()); sets[0].insert(last); it[0] = sets[0].begin(); sol2.push_back(cur1); sol2.push_back(cur2); ans -= last.first; ans += cur1.first + cur2.first; sets[1].erase(sets[1].begin()); sets[2].erase(sets[2].begin()); it[1] = sets[1].begin(); it[2] = sets[2].begin(); flag = true; } } if (!flag) { int ind = to_sort[0].second; sets[ind].erase(sets[ind].begin()); it[ind] = sets[ind].begin(); ans += to_sort[0].first.first; sol3.push_back(to_sort[0].first); } } } cout << ans << "\n"; for (int i = 0; i < sol.size(); i++) cout << sol[i].second << " "; for (int i = 0; i < sol2.size(); i++) cout << sol2[i].second << " "; for (int i = 0; i < sol3.size(); i++) cout << sol3[i].second << " "; cout << "\n"; return 0; }
11
CPP
from heapq import heapify, heappop, heappush import sys input = sys.stdin.buffer.readline def main(): n,k = map(int,input().split()) A = []; B = []; AorB = []; C = [] for __ in range(n): t,a,b = map(int,input().split()) if a == b == 1: C.append(t) elif a == 1: A.append(t) AorB.append(t) elif b == 1: B.append(t) AorB.append(t) if len(A) + len(C) < k or len(B) + len(C) < k: print(-1); exit() A.sort(); B.sort(); C.sort() C = C[:min(k,len(C))] ans = 0 nokori = k - len(C) for i in range(nokori): ans += A[i] + B[i] ab_idx = nokori while C and ab_idx < len(A) and ab_idx < len(B) and C[-1] >= A[ab_idx] + B[ab_idx]: C.pop() ans += A[ab_idx] + B[ab_idx] ab_idx += 1 ans += sum(C) print(ans) if __name__ == '__main__': main()
11
PYTHON3
n,k=map(int,input().split()) aa,bb,cc=[0],[0],[0] for _ in range(n): t,a,b=map(int,input().split()) if a==b and a==1: cc.append(t) elif a==1: aa.append(t) elif b==1: bb.append(t) aa.sort() bb.sort() cc.sort() for i in range(1,len(aa)): aa[i]=aa[i-1]+aa[i] for i in range(1,len(bb)): bb[i]=bb[i-1]+bb[i] for i in range(1,len(cc)): cc[i]=cc[i-1]+cc[i] if len(cc)+len(bb)<k+2 or len(cc)+len(aa)<k+2: print(-1) else: ans=float('inf') for i in range(max(0,k-min(len(aa)-1,len(bb)-1)),min(len(cc),k+1)): ans=min(ans,cc[i]+bb[k-i]+aa[k-i]) print(ans)
11
PYTHON3
n,k = map(int,input().split()) ab = [0] a = [0] b = [0] for i in range(n): t,ai,bi = map(int,input().split()) if ai == 1 and bi == 1: ab.append(t) elif ai == 1: a.append(t) elif bi == 1: b.append(t) if len(ab)-1 + len(a)-1 < k or len(ab)-1 + len(b)-1 < k: print(-1) else: ab.sort() a.sort() b.sort() for j in range(len(ab)-1): ab[j+1] = ab[j] + ab[j+1] for l in range(len(a)-1): a[l+1] = a[l] + a[l+1] for m in range(len(b)-1): b[m+1] = b[m] + b[m+1] ab_read = min(len(ab)-1,k) a_read = max(k-ab_read,0) b_read = max(k-ab_read,0) ans = ab[ab_read]+a[a_read]+b[b_read] for x in range(min(ab_read,len(a)-a_read-1,len(b)-b_read-1)): ab_read-=1 a_read+=1 b_read+=1 check = ab[ab_read]+a[a_read]+b[b_read] if check < ans: ans = check 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 or 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]) result.sort(key=lambda x: x[3]) 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
#!/usr/bin/env python3 import sys input = sys.stdin.readline n, k = map(int, input().split()) both = [] alice = [] bob = [] for _ in range(n): c, a, b = map(int, input().split()) if a and b: both.append(c) elif a: alice.append(c) elif b: bob.append(c) alice.sort() bob.sort() for a, b in zip(alice, bob): both.append(a + b) both.sort() if len(both) < k: print(-1) else: print(sum(both[:k]))
11
PYTHON3
n, k = map(int, input().split()) a = [] b = [] s = [] for i in ' ' * n: t, x, y = map(int, input().split()) if x & y: s += [t] elif x: a += [t] elif y: b += [t] s += [i + j for i, j in zip(sorted(a), sorted(b))] print(-1 if len(s) < k else sum(sorted(s)[:k]))
11
PYTHON3
n,k=map(int,input().split()) l=[] common=[] alice=[] bob=[] for i in range(0,n): t,a,b=map(int,input().split()) if(a&b): common.append(t) elif(a): alice.append(t) elif(b): bob.append(t) if(len(alice)+len(common)<k or len(bob)+len(common)<k): print(-1) else: common.sort() alice.sort() bob.sort() for i in range(0,min(len(alice),len(bob))): common.append(alice[i]+bob[i]) common.sort() if(len(common)>=k): print(sum(common[0:k])) else: print(-1)
11
PYTHON3
n,k = input().split(' ') n,k = int(n), int(k) S = [] for i in range(n): S.append(input().split(' ')) A = [] B = [] C = [] for i in S: if i[1] == '1' and i[2] == '1': C.append(int(i[0])) elif i[1] == '1' and i[2] == '0': A.append(int(i[0])) elif i[1] == '0' and i[2] == '1': B.append(int(i[0])) m = min(len(A),len(B)) if len(C) + m < k: print(-1) else: A.sort() B.sort() for i in range(m): C.append(A[i]+B[i]) ans = 0 C.sort() for i in range(k): ans+=C[i] print(ans)
11
PYTHON3
n,kk = map(int,input().split()) alice = [] bob = [] both =[] 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() both.sort() count=0 l = min(len(alice),len(bob)) i=0 j=0 k=0 ans=0 if len(both)+len(bob)<kk or len(alice)+len(both)<kk: print(-1) else: while j<l and count<kk: if k>=len(both) or alice[j]+bob[j] < both[k]: ans+=alice[j]+bob[j] j+=1 count+=1 else: ans+=both[k] k+=1 count+=1 print(ans+sum(both[k:k+kk-count]))
11
PYTHON3
n, k = map(int, input().split()) a = [] b = [] ab = [] for i in ' ' * n: t, x, y = map(int, input().split()) if x & y: ab += [t] elif x: a += [t] elif y: b += [t] for i, j in zip(sorted(a), sorted(b)): ab += [i + j] if len(ab) < k: print(-1) else: print(sum(sorted(ab)[:k]))
11
PYTHON3
import sys input=sys.stdin.readline n,k=map(int,input().split()) both=[] ali=[] bli=[] for i in range(n): t,a,b=map(int,input().split()) if(a==1 and b==1): both.append(t) if(a==1 and b==0): ali.append(t) if(a==0 and b==1): bli.append(t) lboth=len(both) lali=len(ali) lbli=len(bli) if(lboth+lali<k or lboth+lbli<k): print(-1) else: both.sort(reverse=True) ali.sort(reverse=True) bli.sort(reverse=True) ans=0 for i in range(k): if(lboth!=0 and lali!=0 and lbli!=0): if(both[-1]<=ali[-1]+bli[-1]): ans+=both[-1] both.pop() lboth-=1 else: ans+=(ali[-1]+bli[-1]) lali-=1 lbli-=1 ali.pop() bli.pop() elif(lboth==0): ans+=(ali[-1]+bli[-1]) lali-=1 lbli-=1 ali.pop() bli.pop() elif(lali==0 or lbli==0): ans+=both[-1] both.pop() lboth-=1 print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; long long n, k, t, a, b, boths, alices, bobs, cnt[2], ans; vector<int> both, alice, bob; int main() { ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); cin >> n >> k; for (int i = 0; i < n; i++) { 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); } boths = both.size(); alices = alice.size(); bobs = bob.size(); sort(both.begin(), both.end()); sort(alice.begin(), alice.end()); sort(bob.begin(), bob.end()); while (k) { int s1 = 1 << 30, s2 = 1 << 30; if (boths <= cnt[0]) break; if (boths > cnt[0]) s1 = both[cnt[0]]; if (cnt[1] < min(alices, bobs)) s2 = alice[cnt[1]] + bob[cnt[1]]; if (s1 < s2) ans += s1, cnt[0]++, k--; else ans += s2, cnt[1]++, k--; } while (k--) { if (cnt[1] < min(alices, bobs)) ans += alice[cnt[1]] + bob[cnt[1]], cnt[1]++; else return cout << "-1\n", 0; } cout << ans << '\n'; return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; using ll = long long int; using dl = double; const int N = 2e5 + 10; ll aarray[200000 + 10]; ll magic[101][101]; vector<ll> primes; bool prime[1000001]; int main() { ios_base::sync_with_stdio(false); string str; ll c, d, e, f, x, y, k, a, b, t, A = 0, mod, B = 0, L, j, i, l, r, m, n, C = 0, ans = 0, sum = 0, sum1 = 0; vector<pair<ll, ll>> v, v1; queue<ll> qu; cin >> n >> k; multiset<ll> alice; multiset<ll> bob; multiset<ll> both; ll al = 0; ll bl = 0; for (i = 1; i <= n; i++) { cin >> t >> a >> b; if (a && b) { both.insert(t); al++; bl++; } else if (a) { alice.insert(t); al++; } else if (b) { bob.insert(t); bl++; } } if (al < k || bl < k) { cout << -1 << endl; return 0; } al = k, bl = k; auto ita = alice.begin(); auto itb = bob.begin(); auto itbt = both.begin(); while (al > 0 || bl > 0) { if (al > 0 && bl > 0) { if (ita == alice.end() || itb == bob.end()) { ans += *itbt; itbt++; al--; bl--; } else { if (itbt != both.end()) { if (*ita + *itb < *itbt) { ans += *ita + *itb; ita++; itb++; al--; bl--; } else { ans += *itbt; itbt++; al--; bl--; } } else { ans += *ita + *itb; ita++; itb++; al--; bl--; } } } else if (al > 0) { if (ita == alice.end()) { ans += *itbt; itbt++; al--; bl--; } else if (itbt == both.end()) { ans += *ita; ita++; al--; } else { if (*ita < *itbt) { ans += *ita; ita++; al--; } else { ans += *itbt; itbt++; al--; bl--; } } } else if (bl > 0) { if (itb == bob.end()) { ans += *itbt; itbt++; bl--; al--; } else if (itbt == both.end()) { ans += *itb; itb++; bl--; } else { if (*itb < *itbt) { ans += *itb; itb++; bl--; } else { ans += *itbt; itbt++; bl--; al--; } } } } cout << ans << endl; return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; long long dif(long long a, long long b) { if (a > b) return a - b; else return b - a; } long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL); long long n, k; cin >> n >> k; long long arr[n][3], a = 0, b = 0, c = k, d = k, ans = 0; vector<long long> p, q, r; for (long long i = 0; i < n; i++) { cin >> arr[i][0] >> arr[i][1] >> arr[i][2]; if (arr[i][1] == 1) a++; if (arr[i][2] == 1) b++; if (arr[i][1] == 1 && arr[i][2] == 1) { p.push_back(arr[i][0]); } else if (arr[i][1] == 1) q.push_back(arr[i][0]); else if (arr[i][2] == 1) r.push_back(arr[i][0]); } if (a < k || b < k) { cout << -1; return 0; } sort(q.begin(), q.end()); sort(r.begin(), r.end()); for (long long i = 0; i < min(q.size(), r.size()); i++) { p.push_back(q[i] + r[i]); } sort(p.begin(), p.end()); for (long long i = 0; i < k; i++) ans += p[i]; cout << ans << "\n"; return 0; }
11
CPP
class Books: def __init__(self, time, alice_like, bob_like): self.time = time self.alice_like = alice_like self.bob_like = bob_like def solve(): n, k = map(int, input().split()) books = [] for i in range(n): t, a, b = map(int, input().split()) books.append(Books(t, a == 1, b == 1)) books_everybody_like = [] books_alice_like = [] books_bob_like = [] for b in books: if b.alice_like and b.bob_like: books_everybody_like.append(b) elif b.alice_like: books_alice_like.append(b) elif b.bob_like: books_bob_like.append(b) books_alice_like = sorted(books_alice_like, key=lambda x: x.time) books_bob_like = sorted(books_bob_like, key=lambda x: x.time) for a, b in zip(books_alice_like, books_bob_like): books_everybody_like.append(Books(a.time + b.time, True, True)) if len(books_everybody_like) < k: print(-1) return books_everybody_like = sorted(books_everybody_like, key=lambda x: x.time) answer = 0 for i in range(k): answer += books_everybody_like[i].time print(answer) if __name__ == '__main__': solve()
11
PYTHON3
def cta(t,p,r): global ana,iva,an ana[iva[t][p][1]]^=True an+=iva[t][p][0]*r n,m,k=[int(x) for x in input().split()] 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
import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline class Books: def __init__(self, time, alice_like, bob_like): self.time = time self.alice_like = alice_like self.bob_like = bob_like def solve(): n, k = map(int, input().split()) books = [] for i in range(n): t, a, b = map(int, input().split()) books.append(Books(t, a == 1, b == 1)) books_everybody_like = [] books_alice_like = [] books_bob_like = [] for b in books: if b.alice_like and b.bob_like: books_everybody_like.append(b) elif b.alice_like: books_alice_like.append(b) elif b.bob_like: books_bob_like.append(b) books_alice_like = sorted(books_alice_like, key=lambda x: x.time) books_bob_like = sorted(books_bob_like, key=lambda x: x.time) for a, b in zip(books_alice_like, books_bob_like): books_everybody_like.append(Books(a.time + b.time, True, True)) if len(books_everybody_like) < k: print(-1) return books_everybody_like = sorted(books_everybody_like, key=lambda x: x.time) answer = 0 for i in range(k): answer += books_everybody_like[i].time print(answer) if __name__ == '__main__': solve()
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const long long inf = 922337203685477; const long long mininf = -922337203685477; const long long nax = 2e5 + 5; long long n, k, t, x, y; priority_queue<long long, vector<long long>, greater<long long>> pq[5]; long long val(long long x) { if (!pq[x].empty()) { return pq[x].top(); } else { return inf; } } void ers(long long x) { if (!pq[x].empty()) { pq[x].pop(); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n >> k; for (long long i = 1; i <= n; i++) { cin >> t >> x >> y; if (x && y) { pq[3].push(t); } else if (x) { pq[1].push(t); } else if (y) { pq[2].push(t); } } if (pq[1].size() + pq[3].size() >= k && pq[2].size() + pq[3].size() >= k) { long long ans = 0; long long x = 0, y = 0; while (x < k || y < k) { if (val(3) <= val(1) + val(2)) { x++; y++; ans += val(3); ers(3); } else { ans += val(1); ans += val(2); x++; y++; ers(1), ers(2); } } cout << ans << '\n'; } else { cout << -1 << '\n'; } }
11
CPP
import bisect import sys import math input = sys.stdin.readline import functools import heapq from collections import defaultdict ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) ############ ---- Solution ---- ############ def solve(): [n, k] = inlt() bks = [] for i in range(n): [t, a, b] = inlt() bks.append((t, a, b)) bks.sort(key=lambda x: x[0]) aa = [v for v in bks if v[1] == 1 and v[2] == 0][:k] bb = [v for v in bks if v[1] == 0 and v[2] == 1][:k] com = [v for v in bks if v[1] == 1 and v[2] == 1][:k] com_picked = [] for b in com: acount = len(aa) + len(com_picked) bcount = len(bb) + len(com_picked) if acount < k or bcount < k or b[0] < (aa[-1][0] + bb[-1][0]): com_picked.append(b) if acount >= k: aa.pop() if bcount >= k: bb.pop() acount = len(aa) + len(com_picked) bcount = len(bb) + len(com_picked) if acount < k or bcount < k: return -1 res = 0 res += sum(t for t, _, _ in aa) res += sum(t for t, _, _ in bb) res += sum(t for t, _, _ in com_picked) return res if len(sys.argv) > 1 and sys.argv[1].startswith("input"): f = open("./" + sys.argv[1], 'r') input = f.readline res = solve() print(str(res))
11
PYTHON3
def read_ints(): line = input() return [int(e) for e in line.strip().split(' ')] n, k = read_ints() a = [] b = [] t = [] for _ in range(n): it, ia, ib = read_ints() if ia == 1 and ib == 1: t.append(it) elif ia == 1: a.append(it) elif ib == 1: b.append(it) a.sort() b.sort() for i in range(min(len(a), len(b))): t.append(a[i] + b[i]) t.sort() print(-1 if len(t) < k else sum(t[:k]))
11
PYTHON3
from sys import stdin import math A = list(map(int,stdin.readline().split())) n = A[0] k = A[1] oneone=list() onezero=list() zeroone=list() for t in range(0,n): B = list(map(int,stdin.readline().split())) if B[1]==1 and B[2]==1: oneone.append(B[0]) elif B[1]==1 and B[2]==0: onezero.append(B[0]) elif B[1]==0 and B[2]==1: zeroone.append(B[0]) zeroone.sort() onezero.sort() ans=0 DD=list() for K in range(0,min(len(zeroone),len(onezero))): DD.append(zeroone[K]+onezero[K]) oneone=oneone+DD oneone.sort() QQ=0 if len(oneone)<k: print(-1) QQ=1 else: for t in range(0,k): ans+=oneone[t] if QQ==0: print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const long long int INF = (long long int)1e18; const long long int MOD = 1000 * 1000 * 1000 + 7; const long long int maxn = (long long int)1e5 + 10, L = 23; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long int T = 1; while (T--) { long long int n, k; cin >> n >> k; vector<vector<long long int>> tp(3); for (long long int i = 0; i < n; ++i) { long long int t, a, b; cin >> t >> a >> b; if (!a && !b) continue; if (!a && b) tp[0].push_back(t); if (a && !b) tp[1].push_back(t); if (a && b) tp[2].push_back(t); } for (long long int i = 0; i < 3; ++i) sort(tp[i].begin(), tp[i].end()); vector<long long int> dp(tp[2].size(), 0); for (long long int i = 0; i < tp[2].size(); ++i) { dp[i] = (!i ? tp[2][i] : dp[i - 1] + tp[2][i]); } long long int ans = INF, mn = min({k, (long long int)tp[0].size(), (long long int)tp[1].size()}); if (dp.size() >= k) { ans = dp[k - 1]; } long long int a = 0, b = 0; for (long long int i = 0; i < mn; ++i) { a += tp[0][i]; b += tp[1][i]; long long int want = k - i - 2; if (want >= dp.size()) continue; ans = min(ans, (want >= 0 ? dp[want] : 0ll) + a + b); } if (ans == INF) ans = -1; cout << ans << '\n'; } return 0; }
11
CPP
n,ke=[int(i) for i in input().split()] bo=[] a1=[] b1=[] for i in range(n): ti,a,b=[int(i) for i in input().split()] if a==1 and b==1: bo.append([ti,a,b]) elif a==1: a1.append([ti,a,b]) elif b==1: b1.append([ti,a,b]) bo.sort() a1.sort() b1.sort() su=0 i=0 j=0 k=0 f1=0 while ke>0: if i+1>len(bo) or (j+1>len(a1) or k+1>len(b1)): f1=1 break elif bo[i][0]<=a1[j][0]+b1[k][0]: su+=bo[i][0] i+=1 ke-=1 elif bo[i][0]>a1[j][0]+b1[k][0]: su+=a1[j][0]+b1[k][0] ke-=1 j+=1 k+=1 elif bo[i][0]==a1[j][0]+b1[k][0]: if len(bo)>=min(len(a1),len(b1)): su+=bo[i][0] i+=1 ke-=1 else: su+=a1[j][0]+b1[k][0] j+=1 k+=1 ke-=1 if ke>0 and i+1>len(bo) and (j+1>len(a1) and k+1>len(b1)): print(-1) elif f1==0: print(su) else: if i+1>len(bo): if (j+ke<=len(a1) and k+ke<=len(b1)): while ke>0: su+=a1[j][0]+b1[k][0] ke-=1 j+=1 k+=1 print(su) else: print(-1) elif j+1>len(a1) or k+1>len(b1): if i+ke<=len(bo): while ke>0: su+=bo[i][0] i+=1 ke-=1 print(su) else: print(-1) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n, k; cin >> n >> k; vector<long long> first, second, z; while (n--) { long long t, a, b; cin >> t >> a >> b; if (a) if (b) first.push_back(t); else second.push_back(t); else if (b) z.push_back(t); } sort(second.begin(), second.end()); sort(z.begin(), z.end()); for (long long i = 0; i < min(second.size(), z.size()); i++) first.push_back(second[i] + z[i]); sort(first.begin(), first.end()); if (first.size() >= k) cout << accumulate(first.begin(), first.begin() + k, 0ll) << "\n"; else cout << -1 << "\n"; }
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]) 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 = [] calczz = m - (2 * k) - len(tresult1) if calczz > 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 len(none) > 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 len(none) == 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 len(none) == 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 = 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 result.sort(key=lambda x: x[0]) sum1 = 0 for row in result: sum1 = sum1 + row[0] print(sum1) result.sort(key=lambda x: x[3]) print(' '.join([str(row[3]) for row in result]))
11
PYTHON3
from sys import stdin, stdout import heapq as hq from collections import defaultdict t = 1 for tc in range(t): n,k = list(map(int, stdin.readline().split())) lib=[] for nc in range(n): lib.append(tuple(map(int, stdin.readline().split()))) libA=[] libB=[] libAB=[] for book in lib: if book[1]+book[2]==2: libAB.append(book) elif book[1]==1: libA.append(book) elif book[2]==1: libB.append(book) libA=sorted(libA,key=lambda x:x[0]) libB = sorted(libB, key=lambda x: x[0]) libAB = sorted(libAB, key=lambda x: x[0]) res=0 p1=0 p2=0 while k>0 and p1<len(libA) and p1<len(libB) and p2<len(libAB): if libA[p1][0]+libB[p1][0]<libAB[p2][0]: res+=libA[p1][0]+libB[p1][0] p1+=1 k-=1 else: res += libAB[p2][0] p2 += 1 k -= 1 while k>0 and p2<len(libAB): res += libAB[p2][0] p2 += 1 k -= 1 while k>0 and p1<len(libA) and p1<len(libB): res += libA[p1][0] + libB[p1][0] p1 += 1 k -= 1 if k>0: res=-1 stdout.write(str(res))
11
PYTHON3
import sys def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] # testCases = int(input()) # answers = [] # for _ in range(testCases): #take input n, k = input_split() times = [] alice_likes = [] bob_likes = [] for _ in range(n): t, a, b = input_split() times.append(t) alice_likes.append(a) bob_likes.append(b) if (sum(alice_likes) < k or sum(bob_likes)< k): ans = -1 else: #worst case choose all, but possible times_both = [] times_alice = [] times_bob = [] for book in range(n): if alice_likes[book] == 1 and bob_likes[book] == 1: times_both.append(times[book]) elif alice_likes[book] == 1: times_alice.append(times[book]) elif bob_likes[book] == 1: times_bob.append(times[book]) else: pass times_both.sort() times_alice.sort() times_bob.sort() times_both = times_both + [100000]*(n- len(times_both)) times_alice = times_alice + [100000]*(n- len(times_alice)) times_bob = times_bob + [100000]*(n- len(times_bob)) ans = 0 p1, p2, p3 = 0, 0, 0 for i in range(k): if (times_both[p1] <= times_alice[p2] + times_bob[p3]): ans += times_both[p1] p1 += 1 else: ans += times_alice[p2] + times_bob[p3] p2 += 1 p3 += 1 # times_bob print(ans) # answers.append(ans) # print(*answers, sep = '\n')
11
PYTHON3
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; const int N = 2e5 + 5; long long t[N], a[N], b[N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m, k; cin >> n >> m >> k; int cnta = 0, cntb = 0; set<pair<long long, long long> > ab, aa, bb; for (int i = 1; i <= n; ++i) { cin >> t[i] >> a[i] >> b[i]; cnta += a[i], cntb += b[i]; if (a[i] && b[i]) ab.insert({t[i], i}); if (a[i] && !b[i]) aa.insert({t[i], i}); if (!a[i] && b[i]) bb.insert({t[i], i}); } if (cnta < k || cntb < k) cout << -1, exit(0); long long ans = 0; int taken = 0; vector<pair<long long, long long> > checkab, checka, checkb; while (k--) { if (!aa.size() || !bb.size()) checkab.push_back(*ab.begin()), ans += (ab.begin()->first), taken++, ab.erase(ab.begin()); else if (ab.size() && (ab.begin()->first) < (aa.begin()->first) + (bb.begin()->first)) { checkab.push_back(*ab.begin()), ans += (ab.begin()->first), taken++, ab.erase(ab.begin()); } else { checka.push_back(*aa.begin()), checkb.push_back(*bb.begin()), ans += (aa.begin()->first) + (bb.begin()->first), taken += 2, aa.erase(aa.begin()), bb.erase(bb.begin()); } } if (taken <= m) { m -= taken; set<pair<long long, long long> > can; vector<bool> used(n + 5, 0); for (pair<long long, long long> cur : checkab) used[cur.second] = true; for (pair<long long, long long> cur : checka) used[cur.second] = true; for (pair<long long, long long> cur : checkb) used[cur.second] = true; for (int i = 1; i <= n; ++i) { if (!used[i]) can.insert({t[i], i}); } int mn = min((int)aa.size(), (int)bb.size()); vector<int> dop; while (m && can.size()) { bool ok = false; if (!aa.size() || !bb.size() || !checkab.size()) { pair<long long, long long> cur = *can.begin(); ans += cur.first; dop.push_back(cur.second); can.erase(can.begin()); ok = 1; } else if ((aa.begin()->first) + (bb.begin()->first) - checkab.back().first <= (can.begin()->first)) { ans -= checkab.back().first; can.insert(checkab.back()); checkab.pop_back(); ans += (aa.begin()->first) + (bb.begin()->first); can.erase(*aa.begin()); can.erase(*bb.begin()); checka.push_back(*aa.begin()), checkb.push_back(*bb.begin()); aa.erase(aa.begin()), bb.erase(bb.begin()); ok = 1; } else { pair<long long, long long> cur = *can.begin(); ans += cur.first; dop.push_back(cur.second); if (aa.count(cur)) aa.erase(cur); if (bb.count(cur)) bb.erase(cur); can.erase(can.begin()); ok = 1; } if (ok) { m--; continue; } break; } if (m) cout << -1, exit(0); cout << ans << "\n"; for (pair<long long, long long> cur : checkab) cout << cur.second << " "; for (pair<long long, long long> cur : checka) cout << cur.second << " "; for (pair<long long, long long> cur : checkb) cout << cur.second << " "; for (int cur : dop) cout << cur << " "; exit(0); } m = taken - m; if (min((int)checka.size(), (int)ab.size() - (int)checkab.size()) < m) cout << -1, exit(0); while (m--) { ans -= (checka.back().first + checkb.back().first); ans += (ab.begin()->first); checka.pop_back(), checkb.pop_back(), checkab.push_back(*ab.begin()), ab.erase(ab.begin()); } cout << ans << "\n"; for (pair<long long, long long> cur : checkab) cout << cur.second << " "; for (pair<long long, long long> cur : checka) cout << cur.second << " "; for (pair<long long, long long> cur : checkb) cout << cur.second << " "; }
11
CPP
#include <bits/stdc++.h> using namespace std; const int inf = 1 << 30; const long long mod = 1e9 + 7; const long long linf = 1LL << 62; const double EPS = 1e-7; template <class T> void chmin(T& x, T y) { if (x > y) x = y; } template <class T> void chmax(T& x, T y) { if (x < y) x = y; } int n, k; priority_queue<long long, vector<long long>, greater<long long>> pq[3]; int main() { cin >> n >> k; for (int i = 0; i < n; i++) { int t, a, b; cin >> t >> a >> b; if (a == 1 && b == 1) { pq[0].push(t); } else if (a == 1) { pq[1].push(t); } else if (b == 1) { pq[2].push(t); } } if (pq[0].size() + min(pq[1].size(), pq[2].size()) < k) { cout << -1 << endl; return 0; } for (int i = 0; i < 3; i++) pq[i].push(inf); long long ans = 0; while (k--) { long long t1 = pq[0].top(), t2 = pq[1].top() + pq[2].top(); if (t1 < t2) { ans += t1; pq[0].pop(); } else { ans += t2; pq[1].pop(); pq[2].pop(); } } cout << ans << endl; }
11
CPP
# JAI SHREE RAM import math; from collections import * import sys; from functools import reduce def get_ints(): return map(int, input().strip().split()) def get_list(): return list(get_ints()) def getlistofstring(): return list(input().strip().split()) def printxsp(*args): return print(*args, end="") def printsp(*args): return print(*args, end=" ") UGLYMOD = int(1e9)+7; SEXYMOD = 998244353; MAXN = int(1e5) # sys.setrecursionlimit(10**6) # sys.stdin=open("input.txt","r");sys.stdout=open("output.txt","w") # import bisect # for _testcases_ in range(int(input())): alice =[]; bob = []; both = []; n , k = get_ints() for i in range(n): t, a, b = get_ints() if a & b: both.append(t) elif a == 1: alice.append(t) elif b == 1: bob.append(t) if len(both) + min(len(alice), len(bob)) < k: ans = -1 else: bob = sorted(bob) alice = sorted(alice) both = sorted(both) ai = bi = xi = 0 ans = 0 while k: try: X = both[xi] except: X = float('inf') try: A = alice[ai] except: A = float('inf') try: B = bob[bi] except: B = float('inf') # print(alice, bob, both) # print(A, B, X) if (A == float('inf')) or (B == float('inf')): ans += X xi += 1 elif X == float('inf'): ans += A + B ai += 1 bi += 1 elif A + B < X: ans += A + B ai += 1 bi += 1 else: ans += X xi += 1 k -= 1 print(ans) ''' >>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !! THE LOGIC AND APPROACH IS MINE @luctivud ( UDIT GUPTA ) Link may be copy-pasted here if it's taken from other source. DO NOT PLAGIARISE. >>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !! '''
11
PYTHON3
n, k = map(int, input().split()) doubles = [] single_a = [] single_b = [] for i in range(n): t, a, b = map(int, input().split()) if (a == b): if (a == 1): doubles.append(t) else: if (a): single_a.append([t, a, b]) if (b): single_b.append([t, a, b]) single_a.sort(key = lambda x: x[0]) single_b.sort(key = lambda x: x[0]) for i in range(min(len(single_a), len(single_b))): ta = single_a[i][0] tb = single_b[i][0] doubles.append(ta + tb) doubles.sort() time = 0 if (len(doubles) < k): time = -1 else: time = sum(doubles[:k]) print (time)
11
PYTHON3
n,k = map(int,input().split(' ')) book = [[]for i in range(4)] s = [[]for i in range(4)] for i in range(n): t,a,b = map(int,input().split(' ')) book[2*a+b].append(t) for i in range(1,4): book[i].sort() s[i].append(0) for j in book[i]: s[i].append(s[i][len(s[i])-1]+j) ans = int(2e9+1) for i in range(min(k+1,len(s[3]))): if (k-i < len(s[1]) and k-i < len(s[2])): ans = min(ans,s[3][i]+s[1][k-i]+s[2][k-i]) print(-1 if ans==int(2e9+1) else ans)
11
PYTHON3
def solution(): s = input().split() n = int(s[0]) k = int(s[1]) yyLike = [] xqLike = [] bothLike = [] s = 0 for i in range(n): line = input().split() cost = int(line[0]) if line[1] == '1' and line[2] == '1': bothLike.append(cost) elif line[1] == '1': yyLike.append(cost) elif line[2] == '1': xqLike.append(cost) yyLike.sort() xqLike.sort() bothLike.sort() yyLike.reverse() xqLike.reverse() bothLike.reverse() while k > 0 and len(bothLike) > 0: if len(yyLike) > 0 and len(xqLike) > 0: if bothLike[-1] < yyLike[-1] + xqLike[-1]: s += bothLike.pop() k -= 1 else: s += yyLike.pop() s += xqLike.pop() k -= 1 else: k -= 1 s += bothLike.pop() while k > 0: if len(yyLike) == 0 or len(xqLike) == 0: return(-1) k -= 1 s += yyLike.pop() s += xqLike.pop() return(s) print(solution())
11
PYTHON3
n, k = map(int, input().split()) books = [list(map(int, input().split())) for i in range(n)] AB, A, B = [[10**5,0,0]], [[10**5,0,0]], [[10**5,0,0]] for t,a,b in books: if a == 1 and b == 1: AB.append([t,a,b]) elif a == 1 and b == 0: A.append([t,a,b]) elif a == 0 and b == 1: B.append([t,a,b]) AB = list(reversed(sorted(AB))) A = list(reversed(sorted(A))) B = list(reversed(sorted(B))) ans = [] for i in range(k): if len(AB) != 1 and AB[-1][0] < A[-1][0] + B[-1][0]: ans.append(AB.pop()[0]) elif len(A) != 1 and len(B) != 1: ans.append(A.pop()[0]) ans.append(B.pop()[0]) else: print(-1) break else: print(sum(ans))
11
PYTHON3
from sys import stdin from collections import defaultdict n, k = list(map(int, stdin.readline().rstrip().split(" "))) alice = [] bob = [] both = [] for _ in range(n): ti, ai, bi = list(map(int, stdin.readline().rstrip().split(" "))) if ai == 1 and bi == 1: both.append(ti) elif ai == 1: alice.append(ti) elif bi == 1: bob.append(ti) if len(both) + len(alice) < k or len(both) + len(bob) < k: print(-1) raise SystemExit ki = 0 alice.sort() bob.sort() both.sort() takenBooks = [] takenBooksExtra = [] for ele in both: takenBooks.append(ele) ki += 1 if ki >= k: break newIdx = 0 if ki < k: for i in range(min(len(alice), len(bob))): takenBooksExtra.append(alice[i]) takenBooksExtra.append(bob[i]) ki += 1 newIdx = i + 1 if ki == k: break #print(takenBooks) #print(takenBooksExtra) for i in range(newIdx, min(len(alice), len(bob))): if len(takenBooks) == 0: break if alice[i] + bob[i] < takenBooks[-1]: takenBooks.pop() takenBooksExtra.append(alice[i]) takenBooksExtra.append(bob[i]) else: break #print(takenBooks) #print(takenBooksExtra) print(sum(takenBooks) + sum(takenBooksExtra))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; string lowerCase = "abcdefghijklmnopqrstuvwxyz"; string upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const int fx8[] = {+1, +1, +0, -1, -1, -1, +0, +1}; const int fy8[] = {+0, +1, +1, +1, +0, -1, -1, -1}; const int fx4[] = {+1, 0, -1, 0}; const int fy4[] = {0, +1, 0, -1}; int tc, t, a, b, c, m, n, k, cnt, cnt2; vector<int> oo, zo, oz, v; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); tc = 1; while (tc--) { cin >> n >> k; for (int i = 1; i <= n; i++) { cin >> t >> a >> b; if (a && b) oo.push_back(t), v.push_back(t); else if (a) oz.push_back(t); else if (b) zo.push_back(t); } int x = min(oz.size(), zo.size()); if (x + oo.size() < k) { cout << -1 << '\n'; continue; } sort(oo.begin(), oo.end()); sort(oz.begin(), oz.end()); sort(zo.begin(), zo.end()); for (int i = 0; i < x; i++) { v.push_back(oz[i] + zo[i]); } sort(v.begin(), v.end()); long long sum = 0; for (int i = 0; i < k; i++) { sum += v[i]; } cout << sum << '\n'; } return 0; }
11
CPP
#!/bin/python3 import math import os import random import re import sys from collections import defaultdict a = [int(x) for x in input().split() ] n, k = a[0], a[1] ara = [] for i in range(n): ara.append([int(x) for x in input().split() ]) ara = sorted(ara,key=lambda x: x[0]) newAra = [] tmpAra1 = [] tmpAra2 = [] for i in range(n): if ara[i][1] == 1 and ara[i][2] == 1: newAra.append(ara[i]) elif ara[i][1] == 1: tmpAra1.append(ara[i]) elif ara[i][2] == 1: tmpAra2.append(ara[i]) for i in range( min(len(tmpAra1), len(tmpAra2))): newAra.append([ tmpAra1[i][0] + tmpAra2[i][0], 1, 1 ]) newAra = sorted(newAra,key=lambda x: x[0]) if len(newAra) < k: print(-1) else: cnt = 0 for i in range(k): cnt += newAra[i][0] print(cnt)
11
PYTHON3
n,k = map(int,input().split()) ali,bob,both=[],[],[] for i in range(n): r,ai,bi = map(int,input().split()) if ai and bi:both.append(r) elif ai:ali.append(r) elif bi:bob.append(r) ali.sort() bob.sort() for i in range(min(len(ali),len(bob))): both.append(ali[i]+bob[i]) if len(both)<k: print(-1) else: print(sum(sorted(both)[:k]))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; vector<int> both, alice, bob; int both_size = 0, alice_size = 0, bob_size = 0; int main(int argc, char const *argv[]) { cin.sync_with_stdio(false); int N, k; cin >> N >> k; int min_, a, b; for (int i = 0; i < N; i++) { cin >> min_ >> a >> b; if (a == 1 and b == 1) { both.push_back(min_); both_size++; } else if (a == 1 and b == 0) { alice.push_back(min_); alice_size++; } else if (a == 0 and b == 1) { bob.push_back(min_); bob_size++; } } sort(alice.begin(), alice.end()); sort(bob.begin(), bob.end()); int m = min(alice_size, bob_size); both_size += m; if (both_size < k) { cout << "-1\n"; return 0; } for (int i = 0; i < m; i++) { both.push_back(alice[i] + bob[i]); } sort(both.begin(), both.end()); int ans = 0; for (int i = 0; i < k; i++) { ans += both[i]; } cout << ans; return 0; }
11
CPP
INF = float('inf') def tc(): n, k = map(int, input().split()) books = [tuple(map(int, input().split())) for _ in range(n)] alice, bob, both = [], [], [] for t, a, b in books: if a and b: both.append(t) elif a: alice.append(t) elif b: bob.append(t) alice.sort() bob.sort() for a, b in zip(alice, bob): both.append(a + b) both.sort() # if len(bob) > len(alice): # leftover = bob[-(len(bob) - len(alice)):] # elif len(bob) < len(alice): # leftover = alice[-(len(alice) - len(bob)):] # else: # leftover = [] if len(both) < k: print(-1) else: print(sum(both[:k])) tc()
11
PYTHON3
#dt = {} for i in x: dt[i] = dt.get(i,0)+1 import sys;input = sys.stdin.readline inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()] n,k = ip() t,a,b = [0]*n,[0]*n,[0]*n both = [] alice,bob = [],[] for i in range(n): t[i],a[i],b[i] = ip() if a[i] and b[i]: both.append(t[i]) elif a[i]: alice.append(t[i]) elif b[i]: bob.append(t[i]) if a.count(1) < k or b.count(1) < k: print(-1) exit() alice.sort() bob.sort() m = min(len(alice),len(bob)) for i in range(m): both.append(alice[i]+bob[i]) both.sort() print(sum(both[:k]))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; void scan() {} template <class T, class... A> void scan(T& t, A&... a) { cin >> t, scan(a...); } void print() {} template <class T, class... A> void print(T t, A... a) { cout << t, print(a...); } const int MV = 2e5; int n, m, k, ans = INT_MAX, idx, posTake, posRem; vector<pair<int, int> > alice, bob, both, none, merged; vector<int> ai, bi; int main() { cin.sync_with_stdio(0); cin.tie(0); scan(n, m, k); alice.push_back({0, 0}); bob.push_back({0, 0}); both.push_back({0, 0}); none.push_back({0, 0}); for (int i = 1, t, a, b; i <= n; i++) { scan(t, a, b); if (a && b) both.push_back({t, i}); else if (a) alice.push_back({t, i}); else if (b) bob.push_back({t, i}); else none.push_back({t, i}); } sort(both.begin(), both.end()); sort(alice.begin(), alice.end()); sort(bob.begin(), bob.end()); sort(none.begin(), none.end()); int a = 1, b = 1, c = 1; merged.push_back({0, 0}); ai.push_back(0); bi.push_back(0); bob.push_back({INT_MAX, 0}); alice.push_back({INT_MAX, 0}); none.push_back({INT_MAX, 0}); while (true) { if (a == (int)alice.size() - 1 && b == (int)bob.size() - 1 && c == (int)none.size() - 1) break; if (bob[b].first <= alice[a].first && bob[b].first <= none[c].first) { merged.push_back({bob[b].first, bob[b].second}); bi.push_back(bi[(int)bi.size() - 1] + 1); ai.push_back(ai[(int)ai.size() - 1]); b++; } else if (alice[a].first <= bob[b].first && alice[a].first <= none[c].first) { merged.push_back({alice[a].first, alice[a].second}); bi.push_back(bi[(int)bi.size() - 1]); ai.push_back(ai[(int)ai.size() - 1] + 1); a++; } else { merged.push_back({none[c].first, none[c].second}); bi.push_back(bi[(int)bi.size() - 1]); ai.push_back(ai[(int)ai.size() - 1]); c++; } } bob.pop_back(); alice.pop_back(); for (int i = 1; i < (int)both.size(); i++) both[i].first += both[i - 1].first; for (int i = 1; i < (int)alice.size(); i++) alice[i].first += alice[i - 1].first; for (int i = 1; i < (int)bob.size(); i++) bob[i].first += bob[i - 1].first; for (int i = 1; i < (int)merged.size(); i++) merged[i].first += merged[i - 1].first; for (int i = 0; i < min(m + 1, (int)both.size()); i++) { int take = max(0, k - i), rem = m - i - 2 * take; if ((int)bob.size() - 1 < k - i || (int)alice.size() - 1 < k - i || rem < 0) continue; int low = 0, high = (int)merged.size() - 1, target = -1; while (low <= high) { int mid = (low + high) / 2, cnt = mid - min(ai[mid], take) - min(bi[mid], take); if (cnt == rem) { target = mid; break; } else if (cnt < rem) low = mid + 1; else high = mid - 1; } if (target != -1) { int sum = both[i].first + bob[take].first + alice[take].first + merged[target].first - bob[min(bi[target], take)].first - alice[min(ai[target], take)].first; if (ans > sum) { ans = sum; idx = i; posTake = take; posRem = target; } } } if (ans == INT_MAX) print(-1); else { print(ans, '\n'); set<int> s; for (int i = 1; i <= idx; i++) print(both[i].second, ' '); for (int i = 1; i <= posTake; i++) { s.insert(alice[i].second); s.insert(bob[i].second); } for (int i = 1; i <= posRem; i++) { s.insert(merged[i].second); } for (int i : s) print(i, ' '); } }
11
CPP
n, k = input().split() n = int(n) k = int(k) both = [] al = [] bl = [] for i in range(0, n): t, a, b = input().split() t = int(t) a = int(a) b = int(b) if a == b == 1: both.append(t) elif a == 1: al.append(t) elif b == 1: bl.append(t) both.sort() al.sort() bl.sort() result = [] s = 0 j = 0 while j < len(both): i = both[j] if len(al) > s and len(bl) > s and i > al[s] + bl[s]: result.append(al[s]) result.append(bl[s]) s += 1 else: result.append(i) j += 1 k -= 1 if k == 0: break if k > 0: if len(al[s:s+k]) == k and len(bl[s:s+k]) == k: result.extend(al[s : s + k]) result.extend(bl[s : s + k]) print(sum(result)) else: print(-1) else: print(sum(result))
11
PYTHON3
from collections import Counter n, k = map(int, input().split()) dat = [list(map(int, input().split())) for _ in range(n)] x = [v for v, a, b in dat if a and b] y = [v for v, a, b in dat if a and not b] z = [v for v, a, b in dat if not a and b] x.extend(u + v for u, v in zip(sorted(y), sorted(z))) if len(x) < k: print(-1) else: print(sum(sorted(x)[:k]))
11
PYTHON3
n, k = map(int, input().split()) res = 0 a = [] b = [] dp = [] for i in range(n): t, x, y = map(int, input().split()) if x == y == 1: dp.append(t) elif x == 1: a.append(t) elif y==1: b.append(t) a.sort() b.sort() for i in range(min(len(a), len(b))): dp.append(a[i] + b[i]) dp.sort() if len(dp) < k: print(-1) else: print(sum(dp[:k]))
11
PYTHON3
n, k = map(int, input().split()) z11, z01, z10 = [], [], [] for i in range(n): t, a, b = map(int, input().split()) if a == 1 and b == 1: z11.append(t) elif a == 1: z10.append(t) elif b == 1: z01.append(t) i, j = min(k,len(z11)), min(k,len(z01),len(z10)) z11.sort() z10.sort() z01.sort() if i + j < k: print(-1) exit() while i + j > k: if z11[i-1] > z10[j-1] + z01[j-1]: i -= 1 else: j -= 1 print(sum(z11[:i])+sum(z10[:j])+sum(z01[:j]))
11
PYTHON3
n,m,k = input().split(' ') n,m,k = int(n),int(m),int(k) A = [] B = [] C = [] D = [] Ainmax = 0 Binmax = 0 Cinmax = 0 Dinmax = 0 for i in range(n): entry = input().split(' ') if entry[1] == '1' and entry[2] == '1': C.append([int(entry[0]),i+1]) Cinmax+=1 elif entry[1] == '1' and entry[2] == '0': A.append([int(entry[0]),i+1]) Ainmax+=1 elif entry[1] == '0' and entry[2] == '1': B.append([int(entry[0]),i+1]) Binmax+=1 else: D.append([int(entry[0]),i+1]) Dinmax+=1 A.sort(key = lambda x: x[0]) B.sort(key = lambda x: x[0]) C.sort(key = lambda x: x[0]) D.sort(key = lambda x: x[0]) mi = min(Ainmax,Binmax) if len(C) + mi < k: print(-1) elif len(C)<k and 2*k - len(C)>m: print(-1) else: time = 0 Ain = 0 Bin = 0 Cin = 0 Din = 0 ABinmax = min(mi,m-k) for i in range(k): if Ain == ABinmax: Cin += 1 elif Cin == Cinmax or A[Ain][0]+B[Bin][0] <= C[Cin][0]: Ain += 1 Bin += 1 else: Cin += 1 for i in range(m-Ain-Bin-Cin): pot = [] if Ain < Ainmax: pot.append([A[Ain][0],'Ain+=1']) if Bin < Binmax: pot.append([B[Bin][0],'Bin+=1']) if Cin < Cinmax: pot.append([C[Cin][0],'Cin+=1']) if Din < Dinmax: pot.append([D[Din][0],'Din+=1']) if Ain < Ainmax and Bin < Binmax and Cin!=0: pot.append([A[Ain][0] + B[Bin][0] - C[Cin-1][0],'Ain+=1;Bin+=1;Cin-=1']) minpot = 0 for j in range(len(pot)-1): if pot[minpot][0]>pot[j+1][0]: minpot = j+1 exec(pot[minpot][1]) for i in range(Ain): time += A[i][0] for i in range(Bin): time += B[i][0] for i in range(Cin): time += C[i][0] for i in range(Din): time += D[i][0] print(time) for i in range(Ain): print(A[i][1],end = ' ') for i in range(Bin): print(B[i][1],end = ' ') for i in range(Cin): print(C[i][1],end = ' ') for i in range(Din): print(D[i][1],end = ' ')
11
PYTHON3
#include <bits/stdc++.h> using namespace std; void solve() { long long n, k; cin >> n >> k; long long i, j; vector<long long> a, b, c; for (i = 1; i <= n; i++) { long long x, y, z; cin >> x >> y >> z; if (y == 1 && z == 1) { c.push_back(x); } else if (y == 1) { a.push_back(x); } else if (z == 1) { b.push_back(x); } } sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(c.begin(), c.end()); long long x = a.size(); long long y = b.size(); long long z = c.size(); for (i = 1; i < x; i++) a[i] += a[i - 1]; for (i = 1; i < y; i++) b[i] += b[i - 1]; for (i = 1; i < z; i++) c[i] += c[i - 1]; long long ans = 2e18; for (i = 0; i <= k; i++) { long long take = i; long long atake = k - i; long long btake = k - i; if (take > z || atake > x || btake > y) continue; long long temp = 0; if (take) temp += c[take - 1]; if (atake) temp += a[atake - 1]; if (btake) temp += b[btake - 1]; ans = min(ans, temp); } if (ans == 2e18) ans = -1; cout << ans << '\n'; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long tt; tt = 1; while (tt--) { solve(); } }
11
CPP
#include <bits/stdc++.h> using namespace std; using lint = long long int; struct fast_io { fast_io() { cout << fixed << setprecision(20); ios_base::sync_with_stdio(0); cin.tie(nullptr); cout.tie(nullptr); } } _fast_io; void run_case() { int n, k; cin >> n >> k; int ret = INT_MAX; vector<int> type01; vector<int> type10; vector<int> type11; for (int i = 0; i < n; ++i) { int t, a, b; cin >> t >> a >> b; if (a == 1 && b == 0) { type10.push_back(t); } else if (a == 1 && b == 1) { type11.push_back(t); } else if (a == 0 && b == 1) { type01.push_back(t); } } vector<int> t01((int)type01.size() + 1, 0); vector<int> t10((int)type10.size() + 1, 0); vector<int> t11((int)type11.size() + 1, 0); if ((int)type01.size()) sort(type01.begin(), type01.end()); if ((int)type10.size()) sort(type10.begin(), type10.end()); if ((int)type11.size()) sort(type11.begin(), type11.end()); for (int i = 0; i < (int)type01.size(); ++i) { t01[i + 1] += t01[i] + type01[i]; } for (int i = 0; i < (int)type10.size(); ++i) { t10[i + 1] += t10[i] + type10[i]; } for (int i = 0; i < (int)type11.size(); ++i) { t11[i + 1] += t11[i] + type11[i]; } for (int cnt = 0; cnt <= min(k, (int)t11.size() - 1); ++cnt) { if (k - cnt <= (int)t01.size() - 1 && k - cnt <= (int)t10.size() - 1) { int op = t11[cnt] + t10[k - cnt] + t01[k - cnt]; ret = min(ret, op); } } if (ret == INT_MAX) { cout << -1 << '\n'; } else { cout << ret << '\n'; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tests = 1; for (int i = 1; i <= tests; ++i) { run_case(); } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; } template <typename T, size_t size> ostream &operator<<(ostream &os, const array<T, size> &arr) { os << '{'; string sep; for (const auto &x : arr) os << sep << x, sep = ", "; return os << '}'; } template <typename A, typename B> ostream &operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } void dbg_out() { cerr << endl; } template <typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); } using splay_key = int; struct splay_node { splay_node *parent = nullptr, *child[2] = {nullptr, nullptr}; splay_key key; int size = 1; int64_t sum = 0; static int get_size(splay_node *x) { return x == nullptr ? 0 : x->size; } static int64_t get_sum(splay_node *x) { return x == nullptr ? 0 : x->sum; } int parent_index() const { if (parent == nullptr) return -1; return this == parent->child[0] ? 0 : 1; } void set_child(int index, splay_node *x) { child[index] = x; if (x != nullptr) x->parent = this; } void join() { size = get_size(child[0]) + get_size(child[1]) + 1; sum = get_sum(child[0]) + get_sum(child[1]) + key; } }; auto random_address = [] { char *p = new char; delete p; return uint64_t(p); }; mt19937_64 splay_rng(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1)); int64_t splay_count = 0; struct splay_tree { static const int POOL_SIZE = 10000; static vector<splay_node *> node_pool; static vector<splay_node *> pointers_to_delete; static splay_node *new_node(const splay_key &key) { if (node_pool.empty()) { splay_node *ptr = new splay_node[POOL_SIZE]; pointers_to_delete.push_back(ptr); for (int i = POOL_SIZE - 1; i >= 0; i--) node_pool.push_back(ptr + i); } splay_node *node = node_pool.back(); node_pool.pop_back(); node->key = key; node->sum = key; return node; } static void _delete_pointers() { static bool deleted = false; if (!deleted) { for (splay_node *node : pointers_to_delete) delete[] node; deleted = true; } } splay_node *root = nullptr; splay_tree() { atexit(_delete_pointers); } bool empty() const { return root == nullptr; } int size() const { return root == nullptr ? 0 : root->size; } splay_node *set_root(splay_node *x) { if (x != nullptr) x->parent = nullptr; return root = x; } void rotate_up(splay_node *x, bool x_join = true) { splay_node *p = x->parent, *gp = p->parent; int index = x->parent_index(); if (gp == nullptr) set_root(x); else gp->set_child(p->parent_index(), x); p->set_child(index, x->child[!index]); x->set_child(!index, p); p->join(); if (x_join) x->join(); } void splay(splay_node *x) { splay_count++; while (x != root) { splay_node *p = x->parent; if (p != root) rotate_up(x->parent_index() == p->parent_index() ? p : x, false); rotate_up(x, false); } x->join(); } static constexpr double SPLAY_RNG_RANGE = double(splay_rng.max()) + 1.0; static constexpr double LOG_CONSTANT = 2.0; static constexpr double SPLAY_PROBABILITY = 0.25; static const int SIZE_CUTOFF = 100; void check_splay(splay_node *x, int depth) { int n = size(), log_n = 32 - __builtin_clz(n); if (depth > LOG_CONSTANT * log_n || (n < SIZE_CUTOFF && double(splay_rng()) < SPLAY_PROBABILITY * SPLAY_RNG_RANGE)) splay(x); } pair<splay_node *, int> insert(const splay_key &key, bool require_unique = false) { return insert(new_node(key), require_unique); } pair<splay_node *, int> insert(splay_node *x, bool require_unique = false) { if (root == nullptr) return {set_root(x), 0}; splay_node *current = root, *prev = nullptr; int below = 0, depth = 0; while (current != nullptr) { prev = current; depth++; if (current->key < x->key) { below += splay_node::get_size(current->child[0]) + 1; current = current->child[1]; } else { if (require_unique && !(x->key < current->key)) { below += splay_node::get_size(current->child[0]); check_splay(current, depth); return {current, below}; } current = current->child[0]; } } prev->set_child(prev->key < x->key ? 1 : 0, x); check_splay(x, depth); for (splay_node *node = x; node != nullptr; node = node->parent) node->join(); return {x, below}; } splay_node *begin() { if (root == nullptr) return nullptr; splay_node *x = root; int depth = 0; while (x->child[0] != nullptr) { x = x->child[0]; depth++; } check_splay(x, depth); return x; } splay_node *successor(splay_node *x) const { if (x == nullptr) return nullptr; if (x->child[1] != nullptr) { x = x->child[1]; while (x->child[0] != nullptr) x = x->child[0]; return x; } while (x->parent_index() == 1) x = x->parent; return x->parent; } splay_node *predecessor(splay_node *x) const { if (x == nullptr) return nullptr; if (x->child[0] != nullptr) { x = x->child[0]; while (x->child[1] != nullptr) x = x->child[1]; return x; } while (x->parent_index() == 0) x = x->parent; return x->parent; } splay_node *last() { if (root == nullptr) return nullptr; splay_node *x = root; int depth = 0; while (x->child[1] != nullptr) { x = x->child[1]; depth++; } check_splay(x, depth); return x; } void clear() { vector<splay_node *> nodes; nodes.reserve(size()); for (splay_node *node = begin(); node != nullptr; node = successor(node)) nodes.push_back(node); for (splay_node *node : nodes) { *node = splay_node(); node_pool.push_back(node); } set_root(nullptr); } void erase(splay_node *x) { splay_node *new_x = nullptr, *fix_node = nullptr; if (x->child[0] == nullptr || x->child[1] == nullptr) { new_x = x->child[x->child[0] == nullptr ? 1 : 0]; fix_node = x->parent; } else { splay_node *next = successor(x); assert(next != nullptr && next->child[0] == nullptr); new_x = next; fix_node = next->parent == x ? next : next->parent; next->parent->set_child(next->parent_index(), next->child[1]); next->set_child(0, x->child[0]); next->set_child(1, x->child[1]); } if (x == root) set_root(new_x); else x->parent->set_child(x->parent_index(), new_x); int depth = 0; for (splay_node *node = fix_node; node != nullptr; node = node->parent) { node->join(); depth++; } if (fix_node != nullptr) check_splay(fix_node, depth); *x = splay_node(); node_pool.push_back(x); } pair<splay_node *, int> lower_bound(const splay_key &key) { splay_node *current = root, *prev = nullptr, *answer = nullptr; int below = 0, depth = 0; while (current != nullptr) { prev = current; depth++; if (current->key < key) { below += splay_node::get_size(current->child[0]) + 1; current = current->child[1]; } else { answer = current; current = current->child[0]; } } if (prev != nullptr) check_splay(prev, depth); return make_pair(answer, below); } bool contains(const splay_key &key) { splay_node *node = lower_bound(key).first; return node != nullptr && node->key == key; } bool erase(const splay_key &key) { splay_node *x = lower_bound(key).first; if (x == nullptr || x->key != key) return false; erase(x); return true; } splay_node *node_at_index(int index) { if (index < 0 || index >= size()) return nullptr; splay_node *current = root; int depth = 0; while (current != nullptr) { int left_size = splay_node::get_size(current->child[0]); depth++; if (index == left_size) { check_splay(current, depth); return current; } if (index < left_size) { current = current->child[0]; } else { current = current->child[1]; index -= left_size + 1; } } assert(false); } splay_node *query_prefix_key(const splay_key &key) { splay_node *node = lower_bound(key).first; if (node == nullptr) return root; splay(node); return node->child[0]; } splay_node *query_prefix_count(int prefix) { if (prefix <= 0) return nullptr; if (prefix >= size()) return root; splay_node *node = node_at_index(prefix); splay(node); return node->child[0]; } splay_node *query_suffix_key(const splay_key &key) { splay_node *node = lower_bound(key).first; if (node == nullptr) return nullptr; node = predecessor(node); if (node == nullptr) return root; splay(node); return node->child[1]; } splay_node *query_suffix_count(int suffix) { if (suffix <= 0) return root; if (suffix >= size()) return nullptr; splay_node *node = node_at_index(suffix - 1); splay(node); return node->child[1]; } }; vector<splay_node *> splay_tree::node_pool; vector<splay_node *> splay_tree::pointers_to_delete; void print_tree(splay_node *x, int depth = 0) { if (x == nullptr) return; for (int i = 0; i < depth; i++) cerr << ' '; cerr << x->key << " (" << x->size << ", " << x->sum << ")\n"; print_tree(x->child[0], depth + 1); print_tree(x->child[1], depth + 1); } template <typename T1, typename T2> bool maximize(T1 &a, const T2 &b) { if (a < b) { a = b; return true; } return false; } template <typename T1, typename T2> bool minimize(T1 &a, const T2 &b) { if (b < a) { a = b; return true; } return false; } template <typename T> void output_vector(const vector<T> &v, bool add_one = false, int start = -1, int end = -1) { if (start < 0) start = 0; if (end < 0) end = int(v.size()); for (int i = start; i < end; i++) cout << v[i] + (add_one ? 1 : 0) << (i < end - 1 ? ' ' : '\n'); } const int64_t INF64 = int64_t(2e18) + 5; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, M, K; cin >> N >> M >> K; vector<pair<int, int>> A, B, both, neither; for (int i = 0; i < N; i++) { int t, a, b; cin >> t >> a >> b; if (a + b == 2) both.emplace_back(t, i); else if (a == 1) A.emplace_back(t, i); else if (b == 1) B.emplace_back(t, i); else neither.emplace_back(t, i); } sort(A.begin(), A.end()); sort(B.begin(), B.end()); sort(both.begin(), both.end()); sort(neither.begin(), neither.end()); vector<int64_t> A_sum(A.size() + 1, 0); vector<int64_t> B_sum(B.size() + 1, 0); for (int i = 0; i < int(A.size()); i++) A_sum[i + 1] = A_sum[i] + A[i].first; for (int i = 0; i < int(B.size()); i++) B_sum[i + 1] = B_sum[i] + B[i].first; splay_tree tree; for (int i = K + 1; i < int(A.size()); i++) tree.insert(A[i].first); for (int i = K + 1; i < int(B.size()); i++) tree.insert(B[i].first); for (auto &pr : neither) tree.insert(pr.first); int64_t best = INF64; int best_x = -1; int64_t sum = 0; for (int x = 0; x <= int(both.size()); x++) { if (x > 0) sum += both[x - 1].first; int need = K - x; if (need >= 0 && need < int(A.size())) tree.insert(A[need].first); if (need >= 0 && need < int(B.size())) tree.insert(B[need].first); need = max(need, 0); if (int(A.size()) >= need && int(B.size()) >= need && x + 2 * need <= M) { int remain = M - (x + 2 * need); if (remain <= tree.size()) { int64_t extra = splay_node::get_sum(tree.query_prefix_count(remain)); if (minimize(best, sum + A_sum[need] + B_sum[need] + extra)) best_x = x; } } } if (best_x < 0) { cout << -1 << '\n'; return 0; } cout << best << '\n'; vector<int> books; for (int i = 0; i < best_x; i++) books.push_back(both[i].second); int need = max(K - best_x, 0); for (int i = 0; i < need; i++) { books.push_back(A[i].second); books.push_back(B[i].second); } vector<pair<int, int>> everything_else; for (int i = need; i < int(A.size()); i++) everything_else.push_back(A[i]); for (int i = need; i < int(B.size()); i++) everything_else.push_back(B[i]); for (auto &pr : neither) everything_else.push_back(pr); int remain = M - int(books.size()); nth_element(everything_else.begin(), everything_else.begin() + remain, everything_else.end()); for (int i = 0; i < remain; i++) books.push_back(everything_else[i].second); output_vector(books, true); }
11
CPP
initial = input().strip().split(' ') books = int(initial[0]) likes = int(initial[1]) alice_list = [] bob_list = [] both_list = [] for i in range(books): line_input = input().strip().split(' ') time = int(line_input[0]) alice = (int(line_input[1]) == 1) bob = (int(line_input[2]) == 1) if alice and bob: both_list.append(time) elif alice: alice_list.append(time) elif bob: bob_list.append(time) alice_list.sort() bob_list.sort() length = min(len(alice_list), len(bob_list)) separate_list = [] for i in range(length): separate_list.append(alice_list[i] + bob_list[i]) total_list = both_list + separate_list if len(total_list) < likes: print(-1) else: total_list.sort() total = 0 for r in range(likes): total += total_list[r] print(total)
11
PYTHON3
import sys import math def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def MI(): return map(int, sys.stdin.readline().split()) def SI(): return sys.stdin.readline().strip() n,k = MI() x = [] y = [] z = [] o = [] for q in range(n): t,a,b = MI() if a == 1 and b == 1: z.append(t) elif a == 1: x.append(t) elif b == 1: y.append(t) else: o.append(t) x.sort() y.sort() z.sort() x0 = len(x) y0 = len(y) z0 = len(z) if x0+z0<k or y0+z0<k: print(-1) else: ans = 0 l = r = 0 for i in range(k): if l<x0 and l<y0 and r<z0: if x[l]+y[l]<z[r]: ans+=x[l]+y[l] l+=1 else: ans+=z[r] r+=1 elif r<z0: ans+=z[r] r+=1 elif l<x0 and l<y0: ans+=x[l]+y[l] l+=1 print(ans)
11
PYTHON3
from heapq import heappush, heappush, heapify n, k = map(int, input().split()) alice = [] bob = [] both = [] for i in range(n): t, a, b = map(int, input().rstrip().split()) if a == 1 and b == 1: both.append(t) if a == 1 and b == 0: alice.append(t) if a == 0 and b == 1: bob.append(t) if len(alice) + len(both) < k or len(bob) + len(both) < k: print(-1) exit() alice.sort() bob.sort() both.sort() ans = 0 m = len(both) n = min(len(alice), len(bob)) i = 0# for both m j = 0# for individual n while k > 0: both_t = float("inf") ab_t = float("inf") if i < m: both_t = both[i] if j < n: ab_t = alice[j] + bob[j] if both_t <= ab_t: ans += both_t k -= 1 i += 1 else: ans += ab_t j += 1 k -= 1 print(ans)
11
PYTHON3
from typing import List, Tuple def solve(n: int, k: int, tab: List[Tuple[int, int, int]]): both, a_only, b_only = [], [], [] for t, a, b in tab: if a == 1 and b == 1: both.append(t) elif a == 1: a_only.append(t) elif b == 1: b_only.append(t) both.sort() a_only.sort() b_only.sort() idx_both = idx_a_only = idx_b_only = 0 len_both, len_a_only, len_b_only = len(both), len(a_only), len(b_only) times = [] while len(times) < k and idx_both < len_both and idx_a_only < len_a_only and idx_b_only < len_b_only: if both[idx_both] < a_only[idx_a_only] + b_only[idx_b_only]: times.append(both[idx_both]) idx_both += 1 else: times.append(a_only[idx_a_only] + b_only[idx_b_only]) idx_a_only += 1 idx_b_only += 1 while len(times) < k and idx_both < len_both: times.append(both[idx_both]) idx_both += 1 while len(times) < k and idx_a_only < len_a_only and idx_b_only < len_b_only: times.append(a_only[idx_a_only] + b_only[idx_b_only]) idx_a_only += 1 idx_b_only += 1 return sum(times) if len(times) == k else -1 n, k = map(int, input().split()) tab = [] for _ in range(n): t, a, b = map(int, input().split()) tab.append((t, a, b)) print(solve(n, k, tab))
11
PYTHON3
n,k=map(int,input().split()) l=[] ll=[] lll=[] for i in range(n): t,a,b=map(int,input().split()) if a==1 and b==1: l.append(t) elif a==1: ll.append(t) elif b==1: lll.append(t) ll.sort() lll.sort() for i in range(min(len(ll),len(lll))): l.append(ll[i]+lll[i]) we=len(l) if k>we: print(-1) else: l.sort() ans=0 for i in range(k): ans+=l[i] print(ans)
11
PYTHON3
#import math #from functools import lru_cache #import heapq #from collections import defaultdict #from collections import Counter #from collections import deque #from sys import stdout #from sys import setrecursionlimit #setrecursionlimit(10**7) from sys import stdin input = stdin.readline INF = 10**9 + 7 MAX = 10**7 + 7 MOD = 10**9 + 7 n, k = [int(x) for x in input().strip().split()] c, a, b = [], [], [] for ni in range(n): ti, ai, bi = [int(x) for x in input().strip().split()] if(ai ==1 and bi == 1): c.append(ti) elif(ai == 1): a.append(ti) elif(bi == 1): b.append(ti) c.sort(reverse = True) a.sort(reverse = True) b.sort(reverse = True) alen = len(a) blen = len(b) clen = len(c) m = max(0, k - min(alen, blen)) ans = 0 #print(clen, m) if(m>clen): print('-1') else: for mi in range(m): ans += c.pop() ka = k - m kb = k - m while(ka or kb): ca = (c[-1] if c else float('inf')) da = 0 ap, bp = 0, 0 if(ka): da += (a[-1] if a else float('inf')) ap = 1 if(kb): da += (b[-1] if b else float('inf')) bp = 1 if(da<ca): if(ap): ka -= 1 ans += (a.pop() if a else float('inf')) if(bp): kb -= 1 ans += (b.pop() if b else float('inf')) else: ans += (c.pop() if c else float('inf')) if(ap): ka -= 1 if(bp): kb -= 1 print(ans if ans!=float('inf') else '-1')
11
PYTHON3
n, k = map(int, input().split()) a, b, c = [], [], [] for i in range(n): t, x, y = map(int, input().split()) if x==1 and y==1: a.append(t) if x==1 and y==0: b.append(t) if x==0 and y==1: c.append(t) a.sort() b.sort() c.sort() prea, preb, prec = 0, 0, 0 cnt = min(len(b), len(c), k) for i in range(cnt): preb += b[i] prec += c[i] bestans = int(2e9 + 5) if cnt==k: bestans = preb + prec for both in range(min(len(a), k)): prea += a[both] idx = k - both - 1 #print(idx, cnt) if idx<cnt: preb -= b[idx] prec -= c[idx] if idx-1<cnt and prea+preb+prec < bestans: bestans = prea+preb+prec print(bestans) if bestans<=int(2e9) else print(-1)
11
PYTHON3
import sys input = sys.stdin.readline from math import ceil (n, k) = map(int, input().split()) bob = [] alice = [] good = [] for i in range(n): (t, a, b) = map(int, input().split()) if a == 1: if b == 1: good.append(t) else: alice.append(t) else: if b == 1: bob.append(t) alice.sort() bob.sort() good.sort() ma = len(alice); mb = len(bob); mg = len(good) ka = k; kb = k T = 0 ia = 0; ib = 0; ig = 0 while ka > 0 and kb > 0 and ig < mg and ia < ma and ib < mb: if good[ig] <= alice[ia] + bob[ib]: T += good[ig] ig += 1 else: T += alice[ia] + bob[ib] ia += 1 ib += 1 ka -= 1 kb -= 1 if ia == ma: while ka > 0 and ig < mg: T += good[ig] ig += 1 kb -= 1 ka -= 1 elif ib == mb: while kb > 0 and ig < mg: T += good[ig] ig += 1 ka -= 1 kb -= 1 else: while ka > 0 and ia < ma: T += alice[ia] ia += 1 ka -= 1 while kb > 0 and ib < mb: T += bob[ib] ib += 1 kb -= 1 if ka > 0 or kb > 0: print(-1) else: print(T)
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*2+b == 1: L1.append(t) elif a*2+b == 2: L2.append(t) elif a*2+b == 3: L3.append(t) m = min(len(L1), len(L2)) if len(L3) + m < k: print(-1) else: L1.sort() L2.sort() L3.sort() X = [] for i in range(m): X.append(L1[i]+L2[i]) for i in range(len(L3)): X.append(L3[i]) X.sort() print(sum(X[i] for i in range(k)))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int main(int argc, char **argv) { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m, k; cin >> n >> m >> k; vector<int> cnt(5, 0), mark(4, 0), as; vector<pair<long long, long long> > v[4]; long long ret = 1e18, ans = 0; for (int i = 0; i < n; i++) { int x, y, z; cin >> x >> y >> z; v[2 * y + z].push_back({x, i}); } if (min((int)(v[1].size()), (int)(v[2].size())) + (int)(v[3].size()) < k || ((int)(v[3].size()) < k && (int)(v[3].size()) + 2 * (k - (int)(v[3].size())) > m)) { cout << -1 << endl; return 0; } int hi = min(min((int)(v[1].size()), (int)(v[2].size())), k), lo = max(0, k - (int)(v[3].size())); mark[0] = 0, mark[1] = mark[2] = hi, mark[3] = k - hi; for (int i = 0; i < 4; i++) v[i].push_back({2 * 1000000007, n + i}), sort(v[i].begin(), v[i].end()); for (int i = 0; i < 4; i++) for (int j = 0; j < mark[i]; j++) ans += v[i][j].first; while (hi + k > m) { ans -= v[1][hi - 1].first + v[2][hi - 1].first - v[3][k - hi].first, hi--; mark[1] = mark[2] = hi, mark[3] = k - hi; } for (int i = 0; i < 4; i++) cnt[i] = mark[i]; for (int i = 0; i < m - (hi + k); i++) { int qw = 2 * 1000000007, in; for (int j = 0; j < 4; j++) if (qw > v[j][cnt[j]].first) qw = v[j][cnt[j]].first, in = j; ans += qw, cnt[in]++; } ret = min(ret, ans), as = cnt; for (int i = hi - 1; i >= lo; i--) { int temp = 0; if (mark[1]-- == cnt[1]) cnt[1]--, temp--, ans -= v[1][cnt[1]].first; if (mark[2]-- == cnt[2]) cnt[2]--, temp--, ans -= v[2][cnt[2]].first; while (temp < 0) { int qw = 2 * 1000000007, in; for (int j = 0; j < 4; j++) if (qw > v[j][cnt[j]].first) qw = v[j][cnt[j]].first, in = j; ans += qw, cnt[in]++, temp++; } if (mark[3]++ == cnt[3]) { int qw = 0, in = 4; for (int j = 0; j < 4; j++) if (cnt[j] > mark[j] && qw < v[j][cnt[j] - 1].first) qw = v[j][cnt[j] - 1].first, in = j; ans -= qw, cnt[in]--; ans += v[3][cnt[3]].first, cnt[3]++; } if (ret > ans) as = cnt, ret = ans; } cout << ret << endl; for (int i = 0; i < 4; i++) for (int j = 0; j < as[i]; j++) cout << v[i][j].second + 1 << " "; cout << endl; }
11
CPP
n,k=map(int,input().split());alice=[];bob=[];both=[] for i in range(n): t,a,b=map(int,input().split()) if a&b: both.append(t) elif a: alice.append(t) elif b: bob.append(t) alice.sort(); bob.sort(); for i in range(min(len(alice),len(bob))): both.append(alice[i]+bob[i]) print(-1 if(len(both)<k) else sum(sorted(both)[:k])) exit()
11
PYTHON3
#include <bits/stdc++.h> using namespace std; void takeFrom(vector<long long> &x, long long &cnt, long long &ans) { ans += x.back(); x.pop_back(); cnt++; } void takeFrom(vector<long long> &x, long long &cntA, long long &cntB, long long &ans) { ans += x.back(); x.pop_back(); cntA++; cntB++; } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); long long n, k; cin >> n >> k; vector<long long> a, b, ab; long long countAlice = 0, countBob = 0; for (long long i = 0; i < n; i++) { long long tym, alice, bob; cin >> tym >> alice >> bob; if (alice > 0 && bob > 0) { ab.push_back(tym); countAlice++; countBob++; } else if (alice) { a.push_back(tym); countAlice++; } else if (bob) { b.push_back(tym); countBob++; } } if (countAlice < k || countBob < k) return cout << -1, 0; sort(a.begin(), a.end()); reverse(a.begin(), a.end()); sort(b.begin(), b.end()); reverse(b.begin(), b.end()); sort(ab.begin(), ab.end()); reverse(ab.begin(), ab.end()); long long ans = 0; countAlice = countBob = 0; while (countAlice < k || countBob < k) { if (countAlice < k && countBob < k) { if (!a.empty() && !b.empty()) { if (ab.empty()) { takeFrom(a, countAlice, ans); takeFrom(b, countBob, ans); } else { if (a.back() + b.back() < ab.back()) { takeFrom(a, countAlice, ans); takeFrom(b, countBob, ans); } else { takeFrom(ab, countAlice, countBob, ans); } } } else { takeFrom(ab, countAlice, countBob, ans); } } else if (countAlice < k) { if (a.empty()) { takeFrom(ab, countAlice, countBob, ans); } else { if (ab.empty()) { takeFrom(a, countAlice, ans); } else { if (a.back() < ab.back()) { takeFrom(a, countAlice, ans); } else { takeFrom(ab, countAlice, countBob, ans); } } } } else if (countBob < k) { if (b.empty()) { takeFrom(ab, countAlice, countBob, ans); } else { if (ab.empty()) { takeFrom(b, countBob, ans); } else { if (b.back() < ab.back()) { takeFrom(b, countBob, ans); } else { takeFrom(ab, countAlice, countBob, ans); } } } } } cout << ans << '\n'; }
11
CPP
import sys s = sys.stdin.readline().split() n, m, k = int(s[0]), int(s[1]), int(s[2]) ele = False if k == 62308 and m == 164121: ele = False 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 ele: print('Alice') print(len(Alice)) print('Alice') print('Bob') print(len(Bob)) print('Bob') print('Both') print(len(Both)) print('Both') print('none') print(len(none)) print('none') 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 = [] if ele: print('tresult') print(len(tresult)) print(k) print('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 if ele: print('tresult1') print(len(tresult1)) print(k) print('tresult1') Alice1 = Alice[:k] Bob1 = Bob[:k] Alice = Alice[k:] Bob = Bob[k:] corr = [] calczz = m - (2 * k) - len(tresult1) if ele: if calczz > 0: xtr = [] print('h') if len(Alice) > calczz: xtr = Alice[:calczz] else: xtr = Alice print('h') if len(Bob) > calczz: xtr = xtr + Bob[:calczz] else: xtr = xtr + Bob print('h') if len(none) > calczz: xtr = xtr + none[:calczz] else: xtr = xtr + none print('nai') print('h') xtr = xtr[:calczz] xtr.sort(key=lambda x: (x[1], x[2]), reverse=True) print('h') zz = sum(row[1] == row[2] == 0 for row in xtr) else: zz = 0 else: if calczz > 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 len(none) > 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 len(none) == 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 len(none) == 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 = len(tresult1) + len(corr) + len(Alice1) + len(Bob1) q = m - q if ele: print('corr') print(len(corr)) print('corr') print('q') print(q) print('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 result.sort(key=lambda x: x[0]) if ele: result2.sort(key=lambda x: x[0]) print(result2[-1]) print(All[0]) print(sum(row[1] for row in result2)) print(sum(row[2] for row in result2)) print(result[-1]) print(All[q]) print(sum(row[1] for row in result)) print(sum(row[2] for row in result)) sum1 = 0 for row in result: sum1 = sum1 + row[0] print(sum1) result.sort(key=lambda x: x[3]) print(' '.join([str(row[3]) for row in result]))
11
PYTHON3
n, k = map(int, input().split()) common_books = [] alice_books = [] bob_books = [] for i in range(n): duration, alice, bob = map(int, input().split()) if alice and bob: collection = common_books elif alice: collection = alice_books elif bob: collection = bob_books else: collection = None if collection is not None: collection.append(duration) def get0(collection, idx): if idx < len(collection): return collection[idx] return 0 if len(bob_books) + len(common_books) < k or len(alice_books) + len(common_books) < k: print(-1) else: for collection in (common_books, alice_books, bob_books): collection.sort() icom = 0 iali = 0 ibob = 0 ncom = len(common_books) nali = len(alice_books) nbob = len(bob_books) total = 0 for i in range(k): if icom < ncom and get0(alice_books, iali) + get0(bob_books, ibob) >= common_books[icom]: total += common_books[icom] icom += 1 elif iali < nali and ibob < nbob: total += alice_books[iali] total += bob_books[ibob] iali += 1 ibob += 1 else: total += common_books[icom] icom += 1 print(total)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, k; cin >> n >> k; vector<int> v0, v1, v2; for (int i = 0; i < n; i += 1) { int x, y, z; cin >> x >> y >> z; if (y == 1 && z == 1) v0.push_back(x); else if (y != 1 && z == 1) v2.push_back(x); else if (y == 1 && z != 1) v1.push_back(x); } sort(v0.begin(), v0.end()); sort(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); int k1 = 0, k2 = 0, x = 0, y = 0, z = 0, sum = 0, done = 0, n0 = v0.size(), n1 = v1.size(), n2 = v2.size(); while (k1 != k) { if (x >= n0) { if (y >= n1 || z >= n2) { done = 1; cout << -1 << "\n"; break; } else { sum += v1[y] + v2[z]; y++; z++; k1++; k2++; } } else { if (y >= n1 || z >= n2) { sum += v0[x]; x++; k1++; k2++; } else { if (v0[x] > v1[y] + v2[z]) { sum += v1[y] + v2[z]; y++; z++; k1++; k2++; } else { sum += v0[x]; x++; k1++; k2++; } } } } if (!done) { cout << sum << "\n"; } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; using ll = long long; const long long N = 2e5 + 5; long long n, m, k; vector<pair<long long, long long>> type[2][2]; signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m >> k; for (long long i = 1; i <= n; ++i) { long long a, x, y; cin >> a >> x >> y; type[x][y].emplace_back(a, i); } for (long long i = 0; i <= 1; ++i) for (long long j = 0; j <= 1; ++j) sort(begin(type[i][j]), end(type[i][j])); long long ans = INT_MAX; set<long long> trace; for (long long _ = 0; _ < 2; ++_) { long long tot = 0; set<long long> s2; priority_queue<pair<long long, long long>> pq; priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<pair<long long, long long>>> pq1; for (long long i = 0; i <= 1; ++i) { for (long long j = 0; j <= 1; ++j) { if ((i == 0 && j) or (j == 0 && i)) { for (long long p = 0; p < min(k, (long long)type[i][j].size()); ++p) { tot += type[i][j][p].first; s2.insert(type[i][j][p].second); } for (long long p = k; p < (long long)(type[i][j].size()); ++p) { tot += type[i][j][p].first; s2.insert(type[i][j][p].second); pq.push(type[i][j][p]); } } } } for (auto &v : type[0][0]) { tot += v.first; s2.insert(v.second); pq.push(v); } for (long long i = 0; i <= type[1][1].size(); ++i) { if (i) { tot += type[1][1][i - 1].first; s2.insert(type[1][1][i - 1].second); for (long long __ = 0; __ <= 1; ++__) { for (long long j = 0; j <= 1; ++j) if ((__ == 0 && j) or (j == 0 && __)) { if ((long long)(type[__][j].size()) > k - i && k - i >= 0) pq.push(type[__][j][k - i]); } } } if (pq1.size()) { pq.push(pq1.top()); tot += pq1.top().first; s2.insert(pq1.top().second); pq1.pop(); } while (pq.size() && pq.size() > m - i - 2 * max(k - i, 0ll)) { tot -= pq.top().first; s2.erase(pq.top().second); pq1.push(pq.top()); pq.pop(); } if (pq.size() == m - i - 2 * max(k - i, 0ll) && type[1][1].size() >= i && type[1][0].size() >= k - i && type[0][1].size() >= k - i && tot < ans) ans = tot; if (_ == 1 && tot == ans && trace.empty()) trace = s2; } } if (ans == INT_MAX) ans = -1; cout << ans << '\n'; if (ans != -1) for (auto v : trace) cout << v << ' '; }
11
CPP
n, k = map(int, input().split()) t = [] a = [] b = [] n1 = 0 n2 = 0 n3 = 0 for _ in range(n): x, y, z = map(int, input().split()) if y == 1 and z == 1: t.append(x) n1 += 1 elif y == 1: a.append(x) n2 += 1 elif z == 1: b.append(x) n3 += 1 t.sort() a.sort() b.sort() nc = min(n2, n3) c = [a[i] + b[i] for i in range(min(n2, n3))] ans = 0 i = 0 j = 0 while i < n1 and j < nc and k > 0: if t[i] <= c[j]: i += 1 ans += t[i - 1] else: j += 1 ans += c[j - 1] k -= 1 if k == 0: break while k > 0 and i < n1: i += 1 ans += t[i - 1] k -= 1 while k > 0 and j < nc: j += 1 ans += c[j - 1] k -= 1 if k > 0: print(-1) else: print(ans)
11
PYTHON3
n,k=map(int,input().split()) a=[] b=[] ab=[] counta=0 countb=0 for x in range(n): t,p,q=map(int,input().split()) if p==1 and q==1: counta=counta+1 countb=countb+1 ab.append(t) elif p==1 and q!=1: counta=counta+1 a.append(t) elif q==1 and p!=1: countb=countb+1 b.append(t) if counta>=k and countb>=k: a.sort() b.sort() for x in range(min(len(a),len(b))): ab.append(a[x]+b[x]) res=0 ab.sort() for x in range(k): res=res+ab[x] print(res) else: print(-1)
11
PYTHON3
import sys inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n, k = inp[ii: ii + 2]; ii += 2 both, a, b = [], [], [] for i in range(n): x, p, q = inp[ii: ii + 3]; ii += 3 if p and q: both.append(x) elif p: a.append(x) elif q: b.append(x) if len(both) + len(a) < k or len(both) + len(b) < k: print(-1) else: res = 2 * 10**9 both.sort(); a.sort(); b.sort() cnt, tot, i, j = len(both), sum(both[0: min(len(both), k)]), 0, 0 for cnt in range(min(len(both), k), max(k - min(len(a), len(b)), 0) - 1, -1): while i < k - cnt: tot += a[i] i += 1 while j < k - cnt: tot += b[j] j += 1 res = min(res, tot) if cnt > 0: tot -= both[cnt - 1] print(res)
11
PYTHON3
n, k = map(int, input().split()) a, b, ab = [], [], [] for _ in range(n): it, ia, ib = map(int, input().split()) if ia == 1 and ib == 1: ab.append(it) elif ia == 1: a.append(it) elif ib == 1: b.append(it) a.sort() b.sort() nab = [i + j for i, j in zip(a[:min(len(a) + 1, len(b) + 1)], \ b[:min(len(a) + 1, len(b) + 1)])] fab = ab + nab fab.sort() print(sum(fab[:k]) if k <= len(fab) else -1)
11
PYTHON3
seg = [0]*200000 def offset(x): return x + 100000 def upd(node, L, R, pos, val): if L+1 == R: seg[node] += val seg[offset(node)] = seg[node]*L return M = (L+R)//2 if pos < M: upd(node<<1, L, M, pos, val) else: upd(node<<1 | 1, M, R, pos, val) seg[node] = seg[node<<1] + seg[node<<1 | 1] seg[offset(node)] = seg[offset(node<<1)] + seg[offset(node<<1 | 1)] def query(node, L, R, k): if k == 0: return [0, 0] if seg[node] < k: return [seg[offset(node)], seg[node]] if L+1 == R: return [L*k, k] M = (L+R)//2 left = query(node<<1, L, M, k) right = query(node<<1 | 1, M, R, k-left[1]) left[0] += right[0] left[1] += right[1] return left n, m, k = map(int, input().split()) A, B, both, neither = [], [], [], [] for i in range(n): t, a, b = map(int, input().split()) if a == 0 and b == 0: neither.append([t, i+1]) if a == 1 and b == 0: A.append([t, i+1]) if a == 0 and b == 1: B.append([t, i+1]) if a == 1 and b == 1: both.append([t, i+1]) upd(1, 0, 10001, t, 1) A.sort(); B.sort(); both.sort() p1 = min(k, len(both)) p2 = k - p1 if 2*k - p1 > m or p2 > min(len(A), len(B)): print(-1) exit(0) sum, ans, ch = 0, 2**31, p1 for i in range(p1): sum += both[i][0] upd(1, 0, 10001, both[i][0], -1) for i in range(p2): sum += A[i][0] + B[i][0] upd(1, 0, 10001, A[i][0], -1) upd(1, 0, 10001, B[i][0], -1) ans = sum + query(1, 0, 10001, m-2*k+p1)[0] while p1 > 0: if p2 == min(len(A), len(B)): break upd(1, 0, 10001, A[p2][0], -1); sum += A[p2][0] upd(1, 0, 10001, B[p2][0], -1); sum += B[p2][0] upd(1, 0, 10001, both[p1-1][0], 1); sum -= both[p1-1][0] p2 += 1 p1 -= 1 if m - 2*k + p1 < 0: break Q = query(1, 0, 10001, m-2*k+p1) if ans > sum + Q[0]: ans = sum + Q[0] ch = p1 print(ans) ind = [both[i][1] for i in range(ch)] + [A[i][1] for i in range(k-ch)] + [B[i][1] for i in range(k-ch)] st = neither + [both[i] for i in range(ch, len(both))] + [A[i] for i in range(k-ch, len(A))] + [B[i] for i in range(k-ch, len(B))] st.sort() ind += [st[i][1] for i in range(m-2*k+ch)] print(' '.join([str(x) for x in ind]))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { int n, m, k; scanf("%d%d%d", &n, &m, &k); vector<pair<int, int>> a, b, c, z; a.reserve(n); b.reserve(n); c.reserve(n); z.reserve(n); for (int i = 0; i < n; ++i) { int t, xa, xb; scanf("%d%d%d", &t, &xa, &xb); if (xa == 1 && xb == 1) { z.push_back(make_pair(t, i + 1)); } else if (xa == 1 && xb == 0) { a.push_back(make_pair(t, i + 1)); } else if (xa == 0 && xb == 1) { b.push_back(make_pair(t, i + 1)); } else if (xa == 0 && xb == 0) { c.push_back(make_pair(t, i + 1)); } } sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(c.begin(), c.end()); sort(z.begin(), z.end()); if (min(a.size(), b.size()) + z.size() < k) { printf("-1\n"); return 0; } int cz = min<int>(z.size(), k); int ca = k - cz; int cb = k - cz; int cc = 0; if (cz + ca + cb > m) { printf("-1\n"); return 0; } while (ca < a.size() && cb < b.size() && cz > 0) { if (z[cz - 1].first > a[ca].first + b[cb].first) { if (cz + ca + cb + 1 > m) { break; } cz--; ca++; cb++; } else { break; } } while (ca + cb + cc + cz < m) { int tm = 1000000001; if (ca < a.size()) { tm = min<int>(tm, a[ca].first); } if (cb < b.size()) { tm = min<int>(tm, b[cb].first); } if (cc < c.size()) { tm = min<int>(tm, c[cc].first); } if (cz < z.size()) { tm = min<int>(tm, z[cz].first); } if (ca < a.size() && tm == a[ca].first) { ca++; if (cz > 0 && cb < b.size()) { if (z[cz - 1].first > b[cb].first) { cz--; cb++; } } } else if (cb < b.size() && tm == b[cb].first) { cb++; if (cz > 0 && ca < a.size()) { if (z[cz - 1].first > a[ca].first) { cz--; ca++; } } } else if (cc < c.size() && tm == c[cc].first) { cc++; } else if (cz < z.size() && tm == z[cz].first) { cz++; } } long long int answer = 0; vector<int> ans; ans.reserve(n); for (int i = 0; i < cz; ++i) { answer += z[i].first; ans.push_back(z[i].second); } for (int i = 0; i < ca; ++i) { answer += a[i].first; ans.push_back(a[i].second); } for (int i = 0; i < cb; ++i) { answer += b[i].first; ans.push_back(b[i].second); } for (int i = 0; i < cc; ++i) { answer += c[i].first; ans.push_back(c[i].second); } printf("%lld\n", answer); sort(ans.begin(), ans.end()); for (int i = 0; i < ans.size(); ++i) { printf("%d", ans[i]); if (i < ans.size() - 1) { printf(" "); } else { printf("\n"); } } return 0; }
11
CPP
def mi(): return map(int, input().split()) n,k=mi() a,b,ab=[],[],[] for i in range(n): t,al,bl=mi() lab,la,lb = 0,0,0 if al and bl: ab.append(t) elif al: a.append(t) elif bl: b.append(t) b.sort(), a.sort(), ab.sort() la,lb,lab=len(a),len(b),len(ab) for i in range(1, lb): b[i]+=b[i-1] for i in range(1, la): a[i]+=a[i-1] ans = 1e10 if len(a)>=k and len(b)>=k: ans=a[k-1]+b[k-1] for i in range(lab): # print(ab, i, a, k) if i > 0: ab[i] += ab[i-1] if not k-1-i: ans = min(ans, ab[i]) if k-1-i>0 and min(len(a),len(b))>=k-1-i: ans = min(ans, ab[i]+a[k-i-2]+b[k-i-2]) if ans==1e10: ans=-1 print(ans)
11
PYTHON3
n,k = map(int,input().split()) r = k l = [] for _ in range(n): l.append(list(map(int,input().split()))) l1,l2,l3 = [],[],[] for i in l: if i[1] == 1 and i[2] == 1: l1.append(i) elif i[1] == 1: l2.append(i) elif i[2] == 1: l3.append(i) l1.sort(key = lambda x:x[0]) l2.sort(key = lambda x:x[0]) l3.sort(key = lambda x:x[0]) n1,n2,n3 = len(l1),len(l2),len(l3) i,j,k = 0,0,0 a,b,s = 0,0,0 ans = 0 while a < r or b < r: if a < r and b < r: if i < n1 and (j<n2 and k<n3): if s+l1[i][0] < s+l2[j][0]+l3[k][0]: s+=l1[i][0];i+=1;a+=1;b+=1 else: s += l2[j][0] + l3[k][0];j+=1;k+=1;a+=1;b+=1 elif i>=n1 and (j<n2 and k<n3): s += l2[j][0] + l3[k][0];j += 1;k += 1;a += 1;b += 1 elif i < n1 and ( j>=n2 or k>=n3): s+=l1[i][0];i+=1;a+=1;b+=1 else: ans = -1 break elif a < r: if i<n1 and j<n2: if s+l1[i][0] < s+l2[j][0]: s+=l1[i][0];i+=1;a+=1; else: s+=l2[j][0];j+=1;a+=1; elif i>n1 and j<n2: s+=l2[j][0];j+=1;a+=1; elif j>n2 and i<n1: s+l1[i][0];i+=1;a+=1 else: ans = -1 break else: if i<n1 and k<n3: if s+l1[i][0] < s+l[k][0]: s+=l1[i][0];i+=1;b+=1; else: s+=l3[k][0];k+=1;b+=1; elif i>n1 and k<n3: s+=l3[k][0];k+=1;b+=1; elif k>n3 and i<n1: s+l1[i][0];i+=1;b+=1 else: ans = -1 break print(s if a == r and b == r else -1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int64_t n, k, ac = 0, bc = 0; cin >> n >> k; vector<int64_t> main; vector<int64_t> a_array; vector<int64_t> b_array; while (n--) { int64_t t, a, b; cin >> t >> a >> b; if (a == 1) ac += 1; if (b == 1) bc += 1; if (a == 1 && b == 1) main.push_back(t); else { if (a == 1) a_array.push_back(t); if (b == 1) b_array.push_back(t); } } if (ac >= k && bc >= k) { int64_t i, ans = 0; sort(main.begin(), main.end()); sort(a_array.begin(), a_array.end()); sort(b_array.begin(), b_array.end()); int64_t l = 0, m = 0, n = 0; int64_t aSize = a_array.size(); int64_t bSize = b_array.size(); int64_t mSize = main.size(); for (i = 1; i <= k; i++) { if (aSize >= 1 && bSize >= 1) { if (mSize >= 1) { if ((a_array[l] + b_array[m]) <= main[n]) { ans = ans + a_array[l] + b_array[m]; l += 1; m += 1; aSize -= 1; bSize -= 1; } else { ans += main[n]; n += 1; mSize -= 1; } } else { ans = ans + a_array[l] + b_array[m]; l += 1; m += 1; aSize -= 1; bSize -= 1; } } else { ans += main[n]; n += 1; mSize -= 1; } } cout << ans; } else cout << -1; return 0; }
11
CPP
import atexit import io import sys import math from collections import defaultdict,Counter # _INPUT_LINES = sys.stdin.read().splitlines() # input = iter(_INPUT_LINES).__next__ # _OUTPUT_BUFFER = io.StringIO() # sys.stdout = _OUTPUT_BUFFER # @atexit.register # def write(): # sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) # sys.stdout=open("CP3/output.txt",'w') # sys.stdin=open("CP3/input.txt",'r') # m=pow(10,9)+7 n,k=map(int,input().split()) c1=0 c2=0 l1=[] l2=[] l=[] # visit=[0]*n for i in range(n): t,a,b=map(int,input().split()) c1+=a c2+=b if a+b==2: l.append(t) continue if a==1: l1.append(t) if b==1: l2.append(t) # visit[i]=1 if c1<k or c2<k: print(-1) else: l1.sort(reverse=True) l2.sort(reverse=True) l.sort(reverse=True) # print(l) # print(l1) # print(l2) time=0 while k: if len(l1)==0 or len(l2)==0 or (l and l1[-1]+l2[-1]>l[-1]): time+=l.pop() else: time+=l1.pop() time+=l2.pop() k-=1 print(time)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; void solution() { int n, k; cin >> n >> k; vector<int> zero, one, two; for (int i = 0; i < n; i++) { int t1, t2, t3; cin >> t1 >> t2 >> t3; if (t2 == 0 && t3 == 1) { one.push_back(t1); } else if (t2 == 1 && t3 == 0) { zero.push_back(t1); } else if (t2 == 1 && t3 == 1) { two.push_back(t1); } } sort(zero.begin(), zero.end()); sort(one.begin(), one.end()); sort(two.begin(), two.end()); int last = 0; int output = -1; for (int i = 1; i < min(one.size(), zero.size()); i++) { one[i] += one[i - 1]; zero[i] += zero[i - 1]; } for (int i = 0; i <= min(k, (int)two.size()); i++) { last += (i > 0 ? two[i - 1] : 0); if (k - i > min(zero.size(), one.size())) { continue; } int t_output = last + (k - i > 0 ? one[k - i - 1] + zero[k - i - 1] : 0); if (t_output < output || output == -1) { output = t_output; } } cout << output << endl; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int count, counter = 0; count = 1; while (counter++ < count) { solution(); } return 0; }
11
CPP
import sys import collections import heapq def get_ints(): return map(int, sys.stdin.readline().strip().split()) def main(hashtable, k): alice = bob = 0 total = 0 while alice < k or bob < k: if alice < k and bob < k: if hashtable[(1, 1)] and hashtable[(0, 1)] and hashtable[(1, 0)]: if hashtable[(1, 1)][0] < hashtable[(0, 1)][0] + hashtable[(1, 0)][0]: total += heapq.heappop(hashtable[(1, 1)]) alice += 1 bob += 1 else: total += heapq.heappop(hashtable[(0, 1)]) total += heapq.heappop(hashtable[(1, 0)]) alice += 1 bob += 1 elif hashtable[(1, 1)]: total += heapq.heappop(hashtable[(1, 1)]) alice += 1 bob += 1 elif hashtable[(0, 1)] and hashtable[(1, 0)]: total += heapq.heappop(hashtable[(0, 1)]) total += heapq.heappop(hashtable[(1, 0)]) alice += 1 bob += 1 else: print(-1) return -1 print(total) return total if __name__ == "__main__": N, k = get_ints() hashtable = collections.defaultdict(list) for i in range(N): t, a, b = get_ints() heapq.heappush(hashtable[(a, b)], t) main(hashtable, k)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; using Int = int64_t; vector<Int> csum(vector<Int>& v) { vector<Int> r(v.size()); copy(v.begin(), v.end(), r.begin()); for (int i = 1; i < r.size(); ++i) r[i] += r[i - 1]; return r; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); 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
import sys input = sys.stdin.readline n, k = map(int, input().split()) both = [] alice = [] bob = [] for _ in range(n): c, a, b = map(int, input().split()) if a and b: both.append(c) elif a: alice.append(c) elif b: bob.append(c) alice.sort() bob.sort() for a, b in zip(alice, bob): both.append(a + b) both.sort() if len(both) < k: print(-1) else: print(sum(both[:k]))
11
PYTHON3
n,k=map(int,input().split()) tab=[list(map(int,input().split())) for _ in range(n)] x=[] y=[] z=[] for i in range(n): if tab[i][1]==tab[i][2]==1: x.append(tab[i]) elif tab[i][1]==1: y.append(tab[i]) elif tab[i][2]==1: z.append(tab[i]) x.sort() y.sort() z.sort() sx=[0]*(len(x)+1) sy=[0]*(len(y)+1) sz=[0]*(len(z)+1) for i in range(1,len(x)+1): sx[i]=x[i-1][0] for i in range(1,len(y)+1): sy[i]=y[i-1][0] for i in range(1,len(z)+1): sz[i]=z[i-1][0] for i in range(1,len(sx)): sx[i]+=sx[i-1] for i in range(1,len(sy)): sy[i]+=sy[i-1] for i in range(1,len(sz)): sz[i]+=sz[i-1] ans=10**18 for i in range(k+1): if not (0<=i<=len(x) and 0<=k-i<=len(y) and 0<=k-i<=len(z)): continue res=sx[i]+sy[k-i]+sz[k-i] ans=min(ans,res) if ans==10**18: print(-1) else: print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int n, m, k; struct Node { int id, t, a, b; bool friend operator<(Node a, Node b) { return a.t < b.t; } }; vector<Node> v[5]; int sz[5]; int pos[5], anspos[5]; int ans; int main() { cin >> n >> m >> k; for (int i = 1; i <= n; i++) { int t, a, b; cin >> t >> a >> b; v[a * 2 + b].push_back(Node{i, t, a, b}); } for (int i = 0; i <= 3; i++) sort(v[i].begin(), v[i].end()); for (int i = 0; i <= 3; i++) sz[i] = v[i].size(); ans = -1; int tmp = 0; for (auto x : v[3]) tmp += x.t; pos[3] = sz[3]; for (int i = sz[3]; i >= 0; i--) { while (pos[1] + pos[3] < k && pos[1] < sz[1]) { tmp += v[1][pos[1]].t; pos[1]++; } while (pos[2] + pos[3] < k && pos[2] < sz[2]) { tmp += v[2][pos[2]].t; pos[2]++; } int last = m - pos[1] - pos[2] - pos[3] - pos[0]; while (last < 0 && pos[0] > 0) { pos[0]--; tmp -= v[0][pos[0]].t; last++; } while (last > 0) { int fuck = -1; for (int i = 0; i < 4; i++) if (pos[i] < sz[i]) { if (fuck == -1 || v[i][pos[i]].t < v[fuck][pos[fuck]].t) fuck = i; } if (fuck == -1) break; tmp += v[fuck][pos[fuck]].t; pos[fuck]++; last--; } if (last == 0 && pos[1] + pos[3] >= k && pos[2] + pos[3] >= k) { if (ans == -1 || tmp < ans) { ans = tmp; memcpy(anspos, pos, sizeof(pos)); } } pos[3]--; if (pos[3] >= 0) tmp -= v[3][pos[3]].t; } printf("%d\n", ans); if (ans == -1) return 0; vector<int> res; for (int i = 0; i < 4; ++i) { for (int j = 0; j < anspos[i]; ++j) { res.push_back(v[i][j].id); } } for (auto y : res) printf("%d ", y); return 0; }
11
CPP
n, k = map(int, input().split()) d = {"a": [], "b": [], "c": []} for _ in range(n): t, a, b = map(int, input().split()) if (a, b) == (1, 0): d["a"].append(t) if (a, b) == (0, 1): d["b"].append(t) if (a, b) == (1, 1): d["c"].append(t) d["a"].sort() d["b"].sort() d["c"].sort() a = d["a"] b = d["b"] c = d["c"] a1 = [0] b1 = [0] c1 = [0] num = 0 for el in a: num += el a1.append(num) num = 0 for el in b: num += el b1.append(num) num = 0 for el in c: num += el c1.append(num) if len(a) + len(c) < k or len(b) + len(c) < k: print(-1) else: times = [] i = 0 while i <= k: try: temp = c1[i] + a1[k - i] + b1[k - i] times.append(temp) except IndexError: pass finally: i += 1 print(min(times))
11
PYTHON3
n,k=map(int,input().split()) q1=[] q2=[] q3=[] for i in range(n): a,b,c=map(int,input().split()) if b==1 and c==0: q1.append(a) elif b==0 and c==1: q2.append(a) elif b==1 and c==1: q3.append(a) q1.sort() q2.sort() for i in range(min(len(q1),len(q2))): q3.append(q1[i]+q2[i]) if len(q3)<k: print(-1) else: q3.sort() print(sum(q3[:k]))
11
PYTHON3
n,k = map(int,input().split()) obaja = [] bob = [] alice = [] a=0 b=0 for i in range(n): t,a,b = map(int,input().split()) if a == 1: if b == 1: obaja.append(t) else: alice.append(t) elif b == 1: bob.append(t) alice = list(sorted(alice)) bob = list(sorted(bob)) for i in range(min(len(alice),len(bob))): obaja.append(alice[i]+bob[i]) obaja = list(sorted(obaja)) if len(obaja) < k: print(-1) else: ans = 0 for i in range(k): ans += obaja[i] print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; void err(istream_iterator<string> it) {} template <typename T, typename... Args> void err(istream_iterator<string> it, T a, Args... args) { cout << *it << " = " << a << endl; err(++it, args...); } void solve() { int n, k; cin >> n >> k; vector<int> a, b, c; for (int i = 0; i < n; i++) { int t, al, bo; cin >> t >> al >> bo; pair<int, int> temp = make_pair(al, bo); if (temp == make_pair(1, 0)) { a.push_back(t); } else if (temp == make_pair(0, 1)) { b.push_back(t); } else if (temp == make_pair(1, 1)) { c.push_back(t); } } sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(c.begin(), c.end()); int x1 = 0, x2 = 0, ans = 0; int i = 0, j = 0; bool ok = true; while (x1 < k || x2 < k) { if (i == c.size() && j == min(((int)(a).size()), ((int)(b).size()))) { ok = false; break; } if (j == min(((int)(a).size()), ((int)(b).size())) || (i != ((int)(c).size()) && c[i] <= (a[j] + b[j]))) { ans += c[i++]; x1++; x2++; } else { ans += (a[j] + b[j]); j++; x1++; x2++; } } cout << (ok ? ans : -1) << endl; } int main() { ios::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int T = 1; while (T--) solve(); return 0; }
11
CPP
import os import heapq import sys import math import operator from collections import defaultdict from copy import copy from io import BytesIO, IOBase """def gcd(a,b): if b==0: return a else: return gcd(b,a%b)""" """def pw(a,b): result=1 while(b>0): if(b%2==1): result*=a a*=a b//=2 return result""" def inpt(): return [int(k) for k in input().split()] def main(): n,k=map(int,input().split()) a=[] b=[] both=[] for i in range(n): t,aa,bb=map(int,input().split()) if(aa!=0 and aa==bb): both.append(t) elif(aa): a.append(t) elif(bb): b.append(t) a.sort() b.sort() i=0 while(i!=min(len(a),len(b))): both.append(a[i]+b[i]) i+=1 both.sort() #print(both) ans=0 for i in both: if(k==0): break ans+=i k-=1 if(k>0): print(-1) else: print(ans) 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") if __name__ == "__main__": main()
11
PYTHON3
n,k=map(int,input().split()) bot,ali,bob=[],[],[] alicetime,bobtime,count=0,0,0 for i in range(n): t,a,b=map(int,input().split()) if a==1 and b==1: bot.append(t) elif a==1 and b==0: ali.append(t) elif a==0 and b==1: bob.append(t) bot.sort(reverse=True) ali.sort(reverse=True) bob.sort(reverse=True) while len(bot)>0 and len(ali)>0 and len(bob)>0 and alicetime<k and bobtime<k: if bot[-1]<=(ali[-1]+bob[-1]): x=bot.pop() count+=x alicetime+=1 bobtime+=1 else: y=ali.pop() z=bob.pop() count+=(y+z) alicetime+=1 bobtime+=1 if len(bot)==0 and len(ali)>0 and len(bob)>0 and alicetime<k and bobtime<k: while len(ali)>0 and len(bob)>0 and alicetime<k and bobtime<k: y=ali.pop() z=bob.pop() count+=(y+z) alicetime+=1 bobtime+=1 elif len(bot)>0 and (len(ali)==0 or len(bob)==0) and alicetime<k and bobtime<k: while len(bot)>0 and alicetime<k and bobtime<k: x=bot.pop() count+=x alicetime+=1 bobtime+=1 if alicetime!=k or bobtime!=k: print(-1) else: print(count)
11
PYTHON3
def solve(): global B, K both = [b[0] for b in B if b[1] and b[2]] alice = sorted([b[0] for b in B if b[1] and not b[2]]) bob = sorted([b[0] for b in B if b[2] and not b[1]]) for i in range(min(len(alice), len(bob))): both.append(alice[i] + bob[i]) if len(both) < K: return -1 return sum(sorted(both)[:K]) if __name__ == '__main__': # for _ in range(int(input())): N, K = map(int, input().split()) B = [tuple(map(int, input().split())) for _ in range(N)] sol = solve() print(sol)
11
PYTHON3
from sys import stdin, stdout, setrecursionlimit from collections import deque, defaultdict, Counter from heapq import heappush, heappop import math rl = lambda: stdin.readline() rll = lambda: stdin.readline().split() rli = lambda: map(int, stdin.readline().split()) rlf = lambda: map(float, stdin.readline().split()) INF, NINF = float('inf'), float('-inf') def main(): n, k = rli() both, alice, bob = [], [], [] for _ in range(n): t, a, b = rli() if a and b: both.append(t) elif a: alice.append(t) elif b: bob.append(t) both.sort(reverse = True) alice.sort(reverse = True) bob.sort(reverse = True) read, time = 0, 0 while read < k and (alice or bob or both): a = alice[-1] if alice else INF b = bob[-1] if bob else INF bo = both[-1] if both else INF if a + b == INF and bo == INF: break if a + b <= bo: time += a + b alice.pop() bob.pop() else: time += bo both.pop() read += 1 print(time if read == k else -1) stdout.close() if __name__ == "__main__": main()
11
PYTHON3
n , k = map(int,input().split()) both_like = [] alice_like = [] bob_like = [] for i in range(n): t,a,b = map(int,input().split()) if a and b: both_like.append((t,a,b)) elif a : alice_like.append((t,a,b)) elif b: bob_like.append((t,a,b)) alice_like.sort() bob_like.sort() for i in range(min(len(alice_like),len(bob_like))): both_like.append((alice_like[i][0]+bob_like[i][0],1,1)) both_like.sort() if len(both_like)<k: print(-1) else: ans = 0 for i in range(k): ans+=both_like[i][0] print(ans)
11
PYTHON3