solution
stringlengths
11
983k
difficulty
int64
0
21
language
stringclasses
2 values
def main(): (n, k,) = map(int, input().split(' ')) ta = [] tb = [] tc = [] for i in range(n): t, a, b = map(int, input().split(' ')) if a==1 and b==1: tc .append(t) elif a==1: ta.append(t) elif b==1: tb.append(t) ta.sort() tb.sort() tc.sort() if len(ta) + len(tc) < k or len(tb) + len(tc) < k: return -1 ta.append(10**5) tb.append(10 ** 5) tc.append(10 ** 5) na = 0 nb = 0 nc = 0 T = 0 while na+nc<k and nb+nc<k: while tc[nc] <= ta[na] + tb[nb]: T += tc[nc] nc += 1 if na+nc >= k and nb+nc >= k: return T if na+nc<k: T += ta[na] na +=1 if nb+nc<k: T += tb[nb] nb +=1 while nb+nc>=k and na+nc<k: if tc[nc] <= ta[na]: T += tc[nc] nc +=1 else: T += ta[na] na +=1 while na+nc>=k and nb+nc<k: if tc[nc] <= tb[nb]: T += tc[nc] nc +=1 else: T += tb[nb] nb +=1 return T #for _ in range(int(input())): print(main())
11
PYTHON3
''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path import sys from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right from itertools import permutations from datetime import datetime from math import ceil,sqrt,log,gcd def ii():return int(input()) def si():return input() def mi():return map(int,input().split()) def li():return list(mi()) abc='abcdefghijklmnopqrstuvwxyz' mod=1000000007 #mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def bo(i): return ord(i)-ord('a') def solve(): # for _ in range(ii()): n,k=mi() x=[] y=[] z=[] for i in range(n): a=li() if a[1] and a[2]: x.append(a[0]) elif(a[1]==1): y.append(a[0]) elif(a[2]==1): z.append(a[0]) n1=min(len(y),len(z)) x.sort() y.sort() z.sort() for i in range(1,len(x)): x[i]+=x[i-1] for i in range(1,len(y)): y[i]+=y[i-1] for i in range(1,len(z)): z[i]+=z[i-1] if len(x)+n1<k: print('-1') exit(0) ans=inf if(len(x)>=k): ans=x[k-1] n2=0 else: n2=k-len(x)-1 c=0 for i in range(n2,n1): if i>=k: break x2=k-i-1 if(x2<1): ans=min(ans,z[i]+y[i]) else: ans=min(ans,x[x2-1]+z[i]+y[i]) c+=1 print(ans) if __name__ =="__main__": if path.exists('input.txt'): sys.stdin=open('input.txt', 'r') sys.stdout=open('output.txt','w') else: input=sys.stdin.readline solve()
11
PYTHON3
import bisect import collections import copy import functools import heapq import itertools import math import random import re import sys import time import string from typing import * sys.setrecursionlimit(99999) n, k = map(int, input().split()) booksa, booksb, booksc = [], [], [] for _ in range(n): t, a, b = map(int, input().split()) if a == 0 and b == 1: booksb.append(t) if a == 1 and b == 0: booksa.append(t) if a == 1 and b == 1: booksc.append(t) booksa.sort() booksb.sort() booksc.sort() booksa = booksa[:k] booksb = booksb[:k] na = len(booksa) nb = len(booksb) s = sum(booksa) + sum(booksb) cj = 0 while na < k or nb < k: if cj == len(booksc): break s += booksc[cj] cj += 1 na += 1 nb += 1 while na > k and booksa: s -= booksa.pop() na -= 1 while nb > k and booksb: s -= booksb.pop() nb -= 1 while cj < len(booksc) and (booksa or booksb) and na >= k and nb >= k: sc = booksc[cj] cj += 1 sa = 0 sb = 0 if booksa: sa = booksa.pop() if booksb: sb = booksb.pop() if sa + sb > sc: s += sc s -= sa s -= sb else: break if na >= k and nb >= k: print(s) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const int M = 1e2 + 100; const int N = 2e3 + 100; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; long long n, m, t, k, x, y; vector<long long> ab, bb, abb; void slove() { scanf("%lld%lld", &n, &k); ab.clear(), bb.clear(), abb.clear(); for (int i = 0; i < n; i++) { long long t, a, b; scanf("%lld%lld%lld", &t, &a, &b); if (a && b) abb.push_back(t); else if (a) ab.push_back(t); else if (b) bb.push_back(t); } sort(ab.begin(), ab.end(), greater<int>()); sort(bb.begin(), bb.end(), greater<int>()); long long ans = 0; while (ab.size() && bb.size()) { abb.push_back(ab.back() + bb.back()); ab.pop_back(), bb.pop_back(); } sort(abb.begin(), abb.end()); if (abb.size() < k) ans = -1; else for (int i = 0; i < k; i++) ans += abb[i]; printf("%lld\n", ans); return; } int main() { int T = 1; while (T--) { slove(); } return 0; }
11
CPP
n , k = input().split() n , k = int(n) , int(k) both = [] ali = [] bob = [] while n > 0: t , a , b = input().split() t , a , b = int(t) , int(a) , int(b) if a == 1 and b == 1: both.append(t) elif a == 1: ali.append(t) elif b == 1: bob.append(t) n -= 1 ans = 0 both.sort(reverse = True) ali.sort(reverse = True) bob.sort(reverse = True) if len(both) + min(len(ali) , len(bob)) < k: print(-1) else: while k > 0: if len(both) == 0 or (len(ali) * len(bob) > 0 and (ali[-1] + bob[-1]) <= both[-1]): x = ali.pop(-1) y = bob.pop(-1) ans += (x + y) else: x = both.pop(-1) ans += x k -= 1 print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int t[200005], a[200005], b[200005]; pair<int, int> aa[200005], bb[200005], ab[200005]; int sumaa[200005], sumbb[200005], sumab[200005]; int BITcnt[10005], BITsum[10005]; int anss[200005], ccc; vector<int> v[10005]; bool f[200005]; int lowbit(int x) { return x & (-x); } void updatecnt(int x, int d) { while (x <= 10000) { BITcnt[x] += d; x += lowbit(x); } } void updatesum(int x, int d) { while (x <= 10000) { BITsum[x] += d; x += lowbit(x); } } int querycnt(int x) { int ret = 0; while (x) { ret += BITcnt[x]; x -= lowbit(x); } return ret; } int querysum(int x) { int ret = 0; while (x) { ret += BITsum[x]; x -= lowbit(x); } return ret; } bool check(int x, int c) { return querycnt(x) < c; } int binarysearch(int l, int r, int c) { if (l == r) return l; else if (r - l == 1) { if (check(r, c)) return r; return l; } int mid = (l + r) / 2; if (check(mid, c)) return binarysearch(mid, r, c); else return binarysearch(l, mid - 1, c); } int main() { int n, m, k, cnta, cntb, cntab, ans, now, p, pp, qq, ansi; scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= n; i++) scanf("%d%d%d", &t[i], &a[i], &b[i]); cnta = 0; cntb = 0; cntab = 0; for (int i = 1; i <= n; i++) if (a[i] && b[i]) ab[++cntab] = make_pair(t[i], i); else if (a[i]) aa[++cnta] = make_pair(t[i], i); else if (b[i]) bb[++cntb] = make_pair(t[i], i); sort(ab + 1, ab + cntab + 1); sort(aa + 1, aa + cnta + 1); sort(bb + 1, bb + cntb + 1); for (int i = 1; i <= cntab; i++) sumab[i] = sumab[i - 1] + ab[i].first; for (int i = 1; i <= cnta; i++) sumaa[i] = sumaa[i - 1] + aa[i].first; for (int i = 1; i <= cntb; i++) sumbb[i] = sumbb[i - 1] + bb[i].first; for (int i = 1; i <= cntab; i++) { updatecnt(ab[i].first, 1); updatesum(ab[i].first, ab[i].first); } for (int i = k + 1; i <= cnta; i++) { updatecnt(aa[i].first, 1); updatesum(aa[i].first, aa[i].first); } for (int i = k + 1; i <= cntb; i++) { updatecnt(bb[i].first, 1); updatesum(bb[i].first, bb[i].first); } for (int i = 1; i <= n; i++) if (!a[i] && !b[i]) { updatecnt(t[i], 1); updatesum(t[i], t[i]); } ans = 0x7fffffff; for (int i = 0; i <= cntab; i++) { pp = max(0, k - i); qq = max(0, k - i); if (cnta < k - i || cntb < k - i) { if (i < cntab) { updatecnt(ab[i + 1].first, -1); updatesum(ab[i + 1].first, -ab[i + 1].first); } if (pp > 0 && pp <= cnta) { updatecnt(aa[pp].first, 1); updatesum(aa[pp].first, aa[pp].first); } if (qq > 0 && qq <= cntb) { updatecnt(bb[qq].first, 1); updatesum(bb[qq].first, bb[qq].first); } continue; } if (i + pp + qq > m) { if (i < cntab) { updatecnt(ab[i + 1].first, -1); updatesum(ab[i + 1].first, -ab[i + 1].first); } if (pp) { updatecnt(aa[pp].first, 1); updatesum(aa[pp].first, aa[pp].first); } if (qq) { updatecnt(bb[qq].first, 1); updatesum(bb[qq].first, bb[qq].first); } continue; } if (i + pp + qq == m) { if (sumab[i] + sumaa[pp] + sumbb[qq] < ans) { ans = sumab[i] + sumaa[pp] + sumbb[qq]; ansi = i; } } else { p = binarysearch(0, 10000, m - i - pp - qq); if (sumab[i] + sumaa[pp] + sumbb[qq] + querysum(p) + (m - i - pp - qq - querycnt(p)) * (p + 1) < ans) { ans = sumab[i] + sumaa[pp] + sumbb[qq] + querysum(p) + (m - i - pp - qq - querycnt(p)) * (p + 1); ansi = i; } } if (i < cntab) { updatecnt(ab[i + 1].first, -1); updatesum(ab[i + 1].first, -ab[i + 1].first); } if (pp) { updatecnt(aa[pp].first, 1); updatesum(aa[pp].first, aa[pp].first); } if (qq) { updatecnt(bb[qq].first, 1); updatesum(bb[qq].first, bb[qq].first); } } if (ans == 0x7fffffff) printf("-1\n"); else { printf("%d\n", ans); for (int i = 0; i <= 10000; i++) BITcnt[i] = 0; for (int i = 0; i <= 10000; i++) BITsum[i] = 0; for (int i = 1; i <= ansi; i++) { anss[ccc++] = ab[i].second; f[ab[i].second] = true; } for (int i = 1; i <= k - ansi; i++) { anss[ccc++] = aa[i].second; f[aa[i].second] = true; } for (int i = 1; i <= k - ansi; i++) { anss[ccc++] = bb[i].second; f[bb[i].second] = true; } for (int i = 1; i <= n; i++) if (!f[i]) { updatecnt(t[i], 1); updatesum(t[i], t[i]); v[t[i]].push_back(i); } if (ccc != m) { p = binarysearch(0, 10000, m - ccc); int tt = m - ccc - querycnt(p); for (int i = 1; i <= p; i++) for (int j = 0; j < v[i].size(); j++) anss[ccc++] = v[i][j]; for (int i = 0; i < tt; i++) anss[ccc++] = v[p + 1][i]; } for (int i = 0; i < ccc; i++) if (i != ccc - 1) printf("%d ", anss[i]); else printf("%d\n", anss[i]); } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const long long mod2 = 998244353; const long long INF = 1000000001; const long long N = 100001; const long double PI = 3.141593; long double powm(long long base, long long exp) { long long ans = 1; while (exp) { if (exp & 1) ans = (ans * base) % mod; exp >>= 1, base = (base * base) % mod; } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n, k; cin >> n >> k; priority_queue<long long, vector<long long>, greater<long long>> A, B, C; for (long long i = 0; i < n; i++) { long long t, a, b; cin >> t >> a >> b; if (a == 1 && b == 1) C.push(t); else if (a == 1 && b == 0) A.push(t); else if (a == 0 && b == 1) B.push(t); } if (A.size() + C.size() < k || B.size() + C.size() < k) { cout << "-1" << endl; return 0; } long long a = 0, b = 0, fa = 0; while (a < k || b < k) { if (A.size() == 0 && a < k) { a++; b++; fa += C.top(); C.pop(); } else if (C.size() == 0 && a < k) { a++; fa += A.top(); A.pop(); } else if (B.size() == 0 && b < k) { a++; b++; fa += C.top(); C.pop(); } else if (C.size() == 0 && b < k) { b++; fa += B.top(); B.pop(); } else if (A.top() + B.top() > C.top()) { a++; b++; fa += C.top(); C.pop(); } else { a++; b++; fa += A.top(); fa += B.top(); A.pop(); B.pop(); } } cout << fa << endl; }
11
CPP
#include <bits/stdc++.h> using namespace std; const long long MAX = 3e5; long long fen[MAX], cnt[MAX], sum[MAX]; deque<pair<long long, long long> > a, b, s, d, v; multiset<pair<long long, long long> > sol; void add(long long t, long long cur, long long val) { if (cur > 2e4) return; if (t == cur) cnt[t] += val; if (cur == 0) { cur++; add(t, cur, val); return; } sum[cur] += val * t; fen[cur] += val; add(t, cur + (cur & -cur), val); } long long psum(long long n) { if (n == 0) return 0; return sum[n] + psum(n - (n & -n)); } long long pfen(long long n) { if (n == 0) return cnt[0]; return fen[n] + pfen(n - (n & -n)); } long long bin(long long cur, long long l = 0, long long r = 2e4) { if (r < l) return -1; long long mid = (l + r) / 2; if (mid == 0) { if (cnt[mid] >= cur) return 0; return -1; } long long x = psum(mid - 1), y = pfen(mid - 1); if (y >= cur) return bin(cur, l, mid - 1); if (y + cnt[mid] >= cur) return x + (cur - y) * mid; return bin(cur, mid + 1, r); } int main() { long long n, m, k; cin >> n >> m >> k; for (long long i = 0; i < n; i++) { long long x, y, z; cin >> x >> y >> z; add(x, x, 1); if (y == 1 && z == 1) s.push_back({x, i}); else if (y == 0 && z == 0) v.push_back({x, i}); else if (y == 1) a.push_back({x, i}); else if (z == 1) b.push_back({x, i}); } long long t = min((long long)a.size(), min((long long)b.size(), k)); sort(s.begin(), s.end()); sort(a.begin(), a.end()); sort(b.begin(), b.end()); while (s.size() > k) v.push_back(s.back()), s.pop_back(); while (a.size() > t) v.push_back(a.back()), a.pop_back(); while (b.size() > t) v.push_back(b.back()), b.pop_back(); long long ad = 0; long long sum = 0, c = 0, bk = 0; for (auto i : s) add(i.first, i.first, -1), sum += i.first, bk++, c++, ad++; while (c < k && a.size()) { c++; bk += 2; sum += a[0].first; sum += b[0].first; d.push_back(a[0]); d.push_back(b[0]); add(a[0].first, a[0].first, -1); add(b[0].first, b[0].first, -1); a.pop_front(); b.pop_front(); } if (c != k) { cout << -1; return 0; } if (bin(m - bk) != -1) sol.insert({sum + bin(m - bk), ad}); for (long long i = s.size() - 1; i > -1; i--) { ad--; sum -= s[i].first; add(s[i].first, s[i].first, 1); if (a.size()) { bk++; sum += a[0].first; sum += b[0].first; d.push_back(a[0]); d.push_back(b[0]); add(a[0].first, a[0].first, -1); add(b[0].first, b[0].first, -1); a.pop_front(); b.pop_front(); if (c != k || bk > m) continue; if (bin(m - bk) == -1) continue; sol.insert({sum + bin(m - bk), ad}); } } while (sol.size() && (*sol.begin()).first == -1) sol.erase(sol.begin()); if (!sol.size()) { cout << -1; return 0; } c = 0; vector<long long> pr; t = (*sol.begin()).second; if (s.size() < t) { cout << -1; return 0; } while (t--) { pr.push_back(s[0].second); s.pop_front(); } t = k - pr.size(); if (d.size() < 2 * t) { cout << -1; return 0; } while (t--) { pr.push_back(d[0].second); d.pop_front(); pr.push_back(d[0].second); d.pop_front(); } for (auto i : d) v.push_back(i); for (auto i : s) v.push_back(i); for (auto i : a) v.push_back(i); for (auto i : b) v.push_back(i); sort(v.begin(), v.end()); t = m - pr.size(); if (v.size() < t) { cout << -1; return 0; } while (t--) pr.push_back(v[0].second), v.pop_front(); cout << (*sol.begin()).first << endl; for (auto i : pr) cout << i + 1 << " "; return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; namespace IO { const int BUFFER_SIZE = 1 << 15; char input_buffer[BUFFER_SIZE]; size_t input_pos = 0, input_len = 0; char output_buffer[BUFFER_SIZE]; int output_pos = 0; char number_buffer[100]; uint8_t lookup[100]; void _update_input_buffer() { input_len = fread(input_buffer, sizeof(char), BUFFER_SIZE, stdin); input_pos = 0; if (input_len == 0) input_buffer[0] = EOF; } inline char next_char(bool advance = true) { if (input_pos >= input_len) _update_input_buffer(); return input_buffer[advance ? input_pos++ : input_pos]; } inline bool isspace(char c) { return (unsigned char)(c - '\t') < 5 || c == ' '; } inline void read_char(char &c) { while (isspace(next_char(false))) next_char(); c = next_char(); } template <typename T> inline void read_int(T &number) { bool negative = false; number = 0; while (!isdigit(next_char(false))) if (next_char() == '-') negative = true; do { number = 10 * number + (next_char() - '0'); } while (isdigit(next_char(false))); if (negative) number = -number; } template <typename T, typename... Args> inline void read_int(T &number, Args &...args) { read_int(number); read_int(args...); } inline void read_str(string &str) { while (isspace(next_char(false))) next_char(); str.clear(); do { str += next_char(); } while (!isspace(next_char(false))); } void _flush_output() { fwrite(output_buffer, sizeof(char), output_pos, stdout); output_pos = 0; } inline void write_char(char c) { if (output_pos == BUFFER_SIZE) _flush_output(); output_buffer[output_pos++] = c; } template <typename T> inline void write_int(T number, char after = '\0') { if (number < 0) { write_char('-'); number = -number; } int length = 0; while (number >= 10) { uint8_t lookup_value = lookup[number % 100]; number /= 100; number_buffer[length++] = char((lookup_value & 15) + '0'); number_buffer[length++] = char((lookup_value >> 4) + '0'); } if (number != 0 || length == 0) write_char(char(number + '0')); for (int i = length - 1; i >= 0; i--) write_char(number_buffer[i]); if (after) write_char(after); } inline void write_str(const string &str, char after = '\0') { for (char c : str) write_char(c); if (after) write_char(after); } void init() { bool exit_success = atexit(_flush_output) == 0; assert(exit_success); for (int i = 0; i < 100; i++) lookup[i] = uint8_t((i / 10 << 4) + i % 10); } } // namespace IO void solution() { IO::init(); int n, m, k; IO::read_int(n, m, k); vector<pair<int, int>> both, a, b, non; both.push_back({0, 0}); a = both; b = both; non = both; both.pop_back(); for (int i = 1; i <= n; i++) { int t, x, y; IO::read_int(t, x, y); if (x && y) both.emplace_back(t, i); else if (x) a.emplace_back(t, i); else if (y) b.emplace_back(t, i); else non.emplace_back(t, i); } sort(both.begin(), both.end()); sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(non.begin(), non.end()); int sza = a.size() - 1, szb = b.size() - 1, szn = non.size() - 1; vector<int> sa(a.size()), sb(b.size()), sn(non.size()); for (int i = 1; i < a.size(); i++) sa[i] = sa[i - 1] + a[i].first; for (int i = 1; i < b.size(); i++) sb[i] = sb[i - 1] + b[i].first; for (int i = 1; i < non.size(); i++) sn[i] = sn[i - 1] + non[i].first; int kz; auto check = [&](int val, int nums) { if (nums < 0) return pair<bool, int>{false, 0}; int ita = upper_bound(a.begin(), a.end(), pair<int, int>{val, LONG_MAX}) - a.begin(); ita--; int itb = upper_bound(b.begin(), b.end(), pair<int, int>{val, LONG_MAX}) - b.begin(); itb--; int itn = upper_bound(non.begin(), non.end(), pair<int, int>{val, LONG_MAX}) - non.begin(); itn--; int sum = 0; if (ita > kz) sum += sa[ita] - sa[kz]; if (itb > kz) sum += sb[itb] - sb[kz]; ita = max(0, ita - kz); itb = max(0, itb - kz); int use = ita + itb + itn; if (use < nums) return pair<bool, int>{false, 0}; int excess = use - nums; sum += sn[itn] - val * excess; return pair<bool, int>{true, sum}; }; int sum_both = 0; tuple<int, int, int> ans = {LONG_MAX, -1, -1}; for (int i = 0; i <= both.size(); i++) { if (i > 0) sum_both += both[i - 1].first; kz = max(0, k - i); if (kz > sza || kz > szb) continue; if (kz + kz + i > m) continue; if (i + sza + szb + szn < m) continue; int l = 1, r = 10000, pv = -1, temp = -1; while (l <= r) { int mid = (l + r) >> 1; pair<bool, int> ck = check(mid, m - kz * 2 - i); if (ck.first) r = mid - 1, pv = mid, temp = ck.second; else l = mid + 1; } if (pv == -1) continue; ans = min(ans, make_tuple(sum_both + sa[kz] + sb[kz] + temp, i, pv)); } if (get<1>(ans) == -1) cout << -1; else { IO::write_int(get<0>(ans), '\n'); for (int i = 0; i < get<1>(ans); i++) IO::write_int(both[i].second, ' '); kz = k - get<1>(ans); kz = max(0, kz); for (int i = 1; i <= kz; i++) { IO::write_int(a[i].second, ' '); IO::write_int(b[i].second, ' '); } vector<pair<int, int>> v; for (int i = kz + 1; i < a.size(); i++) v.push_back(a[i]); for (int i = kz + 1; i < b.size(); i++) v.push_back(b[i]); for (int i = 1; i < non.size(); i++) v.push_back(non[i]); sort(v.begin(), v.end()); for (int i = 0; i < m - kz * 2 - get<1>(ans); i++) IO::write_int(v[i].second, ' '); } } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); int tc = 1; while (tc--) { solution(); } }
11
CPP
n, k = map(int, input().split()) both = [] a = [] b = [] for _ in range(n): t, ai, bi = map(int, input().split()) if ai == 1 and bi == 1: both.append(t) elif ai == 1: a.append(t) elif bi == 1: b.append(t) both.sort() a.sort() b.sort() for l in [both,a,b]: if len(l) < k: l += [10 ** 10] * (k - len(l)) if len(a) > k: a = a[:k] if len(b) > k: b = b[:k] if len(both) > k: both = both[:k] out = 0 for i in range(k): out += min(a[i] + b[i],both[-i-1]) if out >= 10 ** 10: print(-1) else: print(out)
11
PYTHON3
from sys import stdin, stdout input = stdin.readline print = stdout.write n, k = map(int, input().split()) alice, bob, together = [], [], [] for _ in range(n): t, a, b = map(int, input().split()) if a and b: together += t, elif a: alice += t, elif b: bob += t, sa, sb, st = len(alice), len(bob), len(together) if sa + st < k or sb + st < k: print('-1') exit() sa -= 1 sb -= 1 st -= 1 alice.sort(reverse=True) bob.sort(reverse=True) together.sort(reverse=True) time = 0 for i in range(k): if sa < 0 or sb < 0: time += together[st] st -= 1 elif st < 0: time += alice[sa] + bob[sb] sa -= 1 sb -= 1 else: if together[st] <= alice[sa] + bob[sb]: time += together[st] st -= 1 else: time += alice[sa] + bob[sb] sa -= 1 sb -= 1 print(str(time))
11
PYTHON3
def fn(qa, qb, qc, k): qa.sort() qb.sort() qc.sort() num = 0 ia = ib = ic = 0 na,nb,nc = len(qa),len(qb),len(qc) for i in range(k): if (nc == 0) or (ic >= nc): num += qa[ia] + qb[ib] ia += 1 ib += 1 elif (na == 0) or (nb == 0) or (ia >= na) or (ib >= nb): num += qc[ic] ic += 1 else: if (qa[ia]+qb[ib]) < qc[ic]: num += qa[ia] + qb[ib] ia += 1 ib += 1 else: num += qc[ic] ic += 1 print(num) n,k = list(map(int, input().split(" "))) qa,qb,qc = [],[],[] ca = cb = 0 for i in range(n): t,a,b = list(map(int, input().split(" "))) if (a==1) and (b==1): ca += 1 cb += 1 qc.append(t) elif a==1: ca += 1 qa.append(t) elif b==1: cb += 1 qb.append(t) if (ca < k) or (cb < k): print(-1) else: fn(qa,qb,qc,k)
11
PYTHON3
import sys input=sys.stdin.readline n, k=map(int, input().split()) alice=[] #10 bob=[] #01 both=[] #11 for _ in range(n): r=list(map(int, input().split())) if r[1]==1 and r[2]==0: alice.append(r[0]) elif r[1]==0 and r[2]==1: bob.append(r[0]) elif r[1]==1 and r[2]==1: both.append(r[0]) alice.sort() bob.sort() if len(both)+min(len(alice), len(bob))>=k: for i in range(min(len(alice), len(bob))): both.append(alice[i]+bob[i]) both.sort() print(sum(both[:k])) else: print(-1)
11
PYTHON3
from math import * from copy import * from string import * # alpha = ascii_lowercase from random import * from sys import stdin,stdout from sys import maxsize from operator import * # d = sorted(d.items(), key=itemgetter(1)) from itertools import * from collections import Counter # d = dict(Counter(l)) import math import math import time from queue import Queue # PradeepGhosh_2017076 def seive(n): l=[True] l=l*(n+1) for i in range(2,int(sqrt(n))+1): if(l[i]==True): val=i*i while(val<len(l)): l[val]=False val+=i prime=[] for i in range(2,len(l)): if(l[i]==True): prime.append(i) return prime def dp(l,i,n,val,ans): if(i>=n or val<0): return 1000000 elif(val==0): return 0 else: if(ans[i]==1000000): ans[i]=min(min(1+dp(l,i+1,n,val-l[i],ans),1+dp(l,i,n,val-l[i],ans)),dp(l,i+1,n,val,ans)) return ans[i] from queue import Queue def factors(n): l=[] for i in range(1,int(sqrt(n))+1): if(n%i==0): if(n//i==i): l.append(i) else: l.append(i) l.append(n//i) return l def check1(s,v,x): while(True): if(v not in s): return v else: v-=1 def check2(s,v,x): while(True): if(v not in s): return v else: v+=1 def up(n): j=n-1 while(j>0): if(n%j==0): break j-=1 return j if __name__ == '__main__': n,k=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) bob.sort() alice.sort() both.sort() if(len(alice)==0 or len(bob)==0): if(len(both)<k): print(-1) else: print(sum(both[0:k])) else: i1=0 i2=0 i3=0 c1=0 c2=0 ans=0 while(i1<len(alice) and i2<len(bob) and i3<len(both) and c1<k and c2<k): if(both[i3]<=alice[i1]+bob[i2]): c1+=1 c2+=1 ans+=both[i3] i3+=1 else: c1+=1 c2+=1 ans+=alice[i1] ans+=bob[i2] i1+=1 i2+=1 if(c1==k and c2==k): print(ans) else: if(i1==len(alice) or i2==len(bob)): while(i3<len(both) and c1<k and c2<k): ans+=both[i3] c1+=1 c2+=1 i3+=1 if(c1!=k): print(-1) else: print(ans) else: while(i1<len(alice) and c1<k): ans+=alice[i1] i1+=1 c1+=1 while(i2<len(bob) and c2<k): ans+=bob[i2] i2+=1 c2+=1 if(c1!=k or c2!=k): print(-1) else: print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int lim[4]; vector<pair<int, int> > t[4]; int get() { vector<pair<int, int> > tmp; for (int i = 0; i <= 2; i++) { if (lim[i] != t[i].size()) { tmp.push_back({t[i][lim[i]].first, i}); } } if (tmp.empty()) return 0; sort(tmp.begin(), tmp.end()); lim[tmp[0].second]++; return tmp[0].first; } int main() { ios::sync_with_stdio(0); cin.tie(0); int n, m, k; cin >> n >> m >> k; for (int i = 1; i <= n; i++) { int tmp, a, b; cin >> tmp >> a >> b; t[(a << 1) | b].push_back({tmp, i}); } for (int i = 0; i <= 3; i++) sort(t[i].begin(), t[i].end()); for (int i = int(t[3].size()) - 1; i >= k; i--) { t[0].push_back(t[3][i]); t[3].pop_back(); } sort(t[0].begin(), t[0].end()); lim[3] = t[3].size(); lim[2] = lim[1] = k - lim[3]; lim[0] = 0; int cnt = m - (lim[1] + lim[2] + lim[3]); if (cnt < 0) { cout << -1 << endl; return 0; } int ans = 0; for (auto val : t[3]) ans += val.first; for (int i = 0; i < lim[1]; i++) { if (i == t[1].size() || i == t[2].size()) { cout << -1 << endl; return 0; } ans += t[1][i].first + t[2][i].first; } for (int i = 0; i < cnt; i++) { int tmp = get(); if (tmp) ans += tmp; else { cout << -1 << endl; return 0; } } int minn = ans, pos[4]; for (int i = 0; i <= 3; i++) pos[i] = lim[i]; for (lim[3]--; lim[3] >= 0; lim[3]--) { ans -= t[3][lim[3]].first; int now = k - lim[3]; if (now == t[1].size() + 1 || now == t[2].size() + 1) break; if (now <= lim[1] && now <= lim[2]) { int tmp = get(); if (tmp) ans += tmp; else break; } else { if (now > lim[1]) { ans += t[1][now - 1].first; } if (now > lim[2]) { ans += t[2][now - 1].first; } if (now > lim[1] && now > lim[2]) { if (lim[0] == 0) break; ans -= (t[0][--lim[0]].first); } lim[1] = max(lim[1], now); lim[2] = max(lim[2], now); } if (minn > ans) { minn = ans; for (int i = 0; i <= 3; i++) pos[i] = lim[i]; } } lim[3]++; cout << minn << endl; for (int i = 0; i <= 3; i++) { for (int j = 0; j < pos[i]; j++) { cout << t[i][j].second << " "; } } cout << endl; }
11
CPP
#include <bits/stdc++.h> using namespace std; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; } const long long INF = 1e11; vector<long long> v[2][2]; int main() { cin.tie(0); ios::sync_with_stdio(false); long long N, K; cin >> N >> K; for (int i = 0; i < N; i++) { long long t, a, b; cin >> t >> a >> b; v[a][b].push_back(t); } long long ans = INF; for (int i = 0; i <= 1; i++) { for (int j = 0; j <= 1; j++) { for (int k = 0; k <= K; k++) { v[i][j].push_back(INF); } sort(v[i][j].begin(), v[i][j].end()); } } long long now = 0; for (int i = 0; i < K; i++) { now += v[1][1][i]; } chmin(ans, now); for (int i = 0; i < K; i++) { now -= v[1][1][K - 1 - i]; now += v[0][1][i]; now += v[1][0][i]; chmin(ans, now); } if (ans >= INF) ans = -1; cout << ans << "\n"; return 0; }
11
CPP
def solve(): import sys nk = sys.stdin.readline().split() n = int(nk[0]) k = int(nk[1]) A = [] B = [] both = [] for i in range(n): t,a,b = list(map(int,sys.stdin.readline().split())) if (a == 1 and b == 0): A.append(t) if (a==0 and b == 1): B.append(t) if (a== 1 and b == 1): both.append(t) A = sorted(A) B = sorted(B) both = sorted(both) pA = [0 for _ in range(len(A))] pB = [0 for _ in range(len(B))] p_both = [0 for _ in range(len(both))] if (len(pA) > 0): pA[0] = A[0] if (len(pB) > 0): pB[0] = B[0] if (len(p_both) > 0): p_both[0] = both[0] for i in range(1,len(A)): pA[i] = pA[i-1] + A[i] for i in range(1,len(B)): pB[i] = pB[i-1] + B[i] for i in range(1,len(both)): p_both[i] = p_both[i-1] + both[i] result = 10**10 for i in range(min(len(both)+1,k+1)): num = k-i if (num > len(A) or num > len(B)): continue s = 0 if (i > 0): s+=p_both[i-1] if (num > 0): s+=pA[num-1] + pB[num-1] result = min(result,s) if (result == 10**10): print(-1) else: print(result) solve()
11
PYTHON3
n,k=map(int, input().split()) la=[] lb=[] lt=[] a1=0 b1=0 co=0 for i in range(n): t,a,b=map(int, input().split()) if a==1: if b!=1: la.append(t) a1=a1+1 if b==1: if a!=1: lb.append(t) b1=b1+1 if a==1 and b==1: lt.append(t) if a1<k or b1<k: print(-1) else: la.sort() lb.sort() v=len(lt) lt.sort() lt1=[] if v>k: for i in range(k): lt1.append(lt[i]) else: lt1=lt m=k-len(lt1) co=sum(lt1) co1=0 x=len(la) y=len(lb) for i in range(k): if k>x or k>y: co1=-1 break co1=co1+(la[i]+lb[i]) for i in range(m): if i>x or i>y: co=-1 break co=co+(la[i]+lb[i]) lt1.reverse() j=0 h=m z=len(lt1) while True: if h<x and h<y and j<z: if lt1[j]>(la[h]+lb[h]): co=co-lt1[j] co=co+(la[h]+lb[h]) j=j+1 h=h+1 else: break else: break if co==-1: print(co1) elif co1!=-1: print(min(co,co1)) else: print(co)
11
PYTHON3
import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ n,k=list(map(int,input().split())) both = [] a = [] b = [] for _ in range(n): t, ai, bi = map(int, input().split()) if ai == 1 and bi == 1: both.append(t) elif ai == 1: a.append(t) elif bi == 1: b.append(t) both.sort() a.sort() b.sort() found=True for l in [both,a,b]: if len(l) < k: l += [10 ** 10] * (k - len(l)) if len(a) > k: a = a[:k] if len(b) > k: b = b[:k] if len(both) > k: both = both[:k] out = 0 for i in range(k): out += min(a[i] + b[i],both[-i-1]) if out >= 10 ** 10: print(-1) else: print(out)
11
PYTHON3
import sys; import math; def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def get_string(): return sys.stdin.readline().strip() #def helper(n): n,k = get_ints(); alice = []; bob = []; comm = []; for i in range(n): t,a,b = get_ints(); if(a==1 and b==1): comm.append(t); continue; if(a==1): alice.append(t); if(b==1): bob.append(t); alice.sort();bob.sort(),comm.sort(); #print(alice) #print(bob) #print(comm) ans = 0; ptr1 = 0; ptr2 = 0; fans = [] while(ptr1<min(len(alice),len(bob)) and ptr2<len(comm)): if(alice[ptr1]+bob[ptr1]<comm[ptr2]): fans.append(alice[ptr1]+bob[ptr1]); ptr1+=1; else: fans.append(comm[ptr2]); ptr2+=1; #print(fans); while(ptr1<min(len(alice),len(bob))): fans.append(alice[ptr1]+bob[ptr1]); ptr1+=1; while(ptr2<len(comm)): fans.append(comm[ptr2]); ptr2+=1; if(len(fans)<k): print(-1); else: print(sum(fans[0:k]));
11
PYTHON3
n,k = map(int,input().split()) same = [] different_a = [] different_b = [] for i in range(n): t,x,y = map(int,input().split()) if x==1 and y==1: same.append(t) elif x==1 and y==0: different_a.append(t) elif y==1 and x==0: different_b.append(t) flag=1 if len(same)+len(different_a)<k or len(same)+len(different_b)<k: flag=0 if flag==0: print(-1) else: same.sort() for i in range(1,len(same)): same[i]+=same[i-1] different_a.sort() for i in range(1,len(different_a)): different_a[i]+=different_a[i-1] different_b.sort() for i in range(1,len(different_b)): different_b[i]+=different_b[i-1] i = 0 minn = 10**15 while i<=k: ans1 = 10**15 if i-1>=0 and i-1<len(same): ans1=same[i-1] ans2=10**15 if k-i-1>=0 and k-i-1<len(different_a): ans2 = different_a[k-i-1] ans3 = 10**15 if k-i-1>=0 and k-i-1<len(different_b): ans3= different_b[k-i-1] ans=0 if i==0: ans+= ans2+ans3 elif i==k: ans+= ans1 else: ans+=ans1+ans2+ans3 minn = min(ans,minn) i+=1 print(minn)
11
PYTHON3
from operator import add class SegTree(): def __init__(self, N, e, operator_func=add): self.e = e self.size = N self.node = [self.e] * (2*N) self.operator_func = operator_func def set_list(self, l): for i in range(self.size): self.node[i+self.size-1] = l[i] for i in range(self.size-1)[::-1]: self.node[i] = self.operator_func(self.node[2*i+1], self.node[2*i+2]) def update(self, k, x): k += self.size-1 self.node[k] = x while k >= 0: k = (k - 1) // 2 self.node[k] = self.operator_func(self.node[2*k+1], self.node[2*k+2]) def get(self, l, r): x = self.e l += self.size r += self.size while l<r: if l&1: x = self.operator_func(x, self.node[l-1]) l += 1 if r&1: r -= 1 x = self.operator_func(x, self.node[r-1]) l >>= 1 r >>= 1 return x n, k = map(int, input().split()) l1, l2, l3 = [], [], [] for _ in range(n): t, a, b = map(int, input().split()) if a==0 and b==0: continue elif a and b: l2.append(t) elif a: l1.append(t) else: l3.append(t) l1.sort() l2.sort() l3.sort() s1, s2, s3 = len(l1), len(l2), len(l3) tree1 = SegTree(s1, 0, add) tree2 = SegTree(s2, 0, add) tree3 = SegTree(s3, 0, add) tree1.set_list(l1) tree2.set_list(l2) tree3.set_list(l3) INF = 10**20 ans = INF for i in range(k+1): if i<=s2 and k-i<=s1 and k-i<=s3: p = max(0, k-i) v = tree2.get(0, i)+tree1.get(0, p)+tree3.get(0, p) ans = min(ans, v) print(ans if ans!=INF else -1)
11
PYTHON3
import sys def answer(n, k, t, a, b): t_both = [] t_a = [] t_b = [] for i in range(n): if a[i] == 1 and b[i] == 1: t_both.append(t[i]) elif a[i] == 1: t_a.append(t[i]) elif b[i] == 1: t_b.append(t[i]) if k > ( len(t_both) + min(len(t_a), len(t_b)) ) : return -1 t_both.sort() t_a.sort() t_b.sort() both_ctr = 0 ab_ctr = 0 ans = 0 for i in range(k): best_t_both = 10**5 best_ind = 10**5 if both_ctr < len(t_both): best_t_both = t_both[both_ctr] if ab_ctr < min(len(t_a), len(t_b)): best_ind = t_a[ab_ctr] + t_b[ab_ctr] if best_t_both < best_ind: ans += best_t_both both_ctr += 1 else: ans += best_ind ab_ctr += 1 return ans def main(): n, k = map(int, sys.stdin.readline().split()) t = [0 for _ in range(n)] a = [0 for _ in range(n)] b = [0 for _ in range(n)] for i in range(n): t[i], a[i], b[i] = map(int, sys.stdin.readline().split()) print(answer(n, k, t, a, b)) return main()
11
PYTHON3
a = input().split(" ") list1 = [] list2 = [] list3 = [] for i in range(int(a[0])): b = input().split(" ") if(b[1]=="1"): if(b[2]=="1"): list1.append(int(b[0])) else: list2.append(int(b[0])) else: if(b[2]=="1"): list3.append(int(b[0])) if(len(list1)+min(len(list2),len(list3))<int(a[1])): print(-1) else: ans = 0 ans1 = 0 ans2 = 0 list1_index = 0 list2_index = 0 list3_index = 0 list1_len = len(list1) list2_len = len(list2) list3_len = len(list3) list1.sort() list2.sort() list3.sort() while(ans<int(a[1]) or ans1<int(a[1])): if(ans<int(a[1]) and ans1<int(a[1]) and list1_index<list1_len): if(list2_len<=list2_index or list3_len<=list3_index): tag = int(a[1])-min(ans,ans1) ans2+=sum(list1[list1_index:list1_index+tag]) ans = int(a[1]) ans1 = int(a[1]) else: if(list1[list1_index]>list2[list2_index]+list3[list3_index]): ans1+=1 ans+=1 ans2+=list2[list2_index]+list3[list3_index] list2_index+=1 list3_index+=1 else: ans1+=1 ans+=1 ans2+=list1[list1_index] list1_index+=1 elif(ans<int(a[1])): if(list2_len<=list2_index): ans+=1 ans2+=list1[list1_index] list1_index+=1 else: ans+=1 ans2+=list2[list2_index] list2_index+=1 elif(ans1<int(a[1])): if(list3_len<=list3_index): ans1+=1 ans2+=list1[list1_index] list1_index+=1 else: ans1+=1 ans2+=list3[list3_index] list3_index+=1 print(ans2)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int const MAXN = 2e5 + 10; int n, m, T, k; vector<pair<int, int>> a, b, ab, other; vector<int> ans; int check(int mid) { if ((int)a.size() < k - mid) return 2e9 + 1; if ((int)b.size() < k - mid) return 2e9 + 1; if (mid + max(0, k - mid) * 2 > m) return 2e9 + 1; int nd = m - mid, res = 0; ans.clear(); vector<pair<int, int>> vec; for (int i = 0; i < mid; i++) res += ab[i].first, ans.push_back(ab[i].second); for (int i = mid; i < ab.size(); i++) vec.push_back(ab[i]); for (int i = 0; i < k - mid; i++) res += a[i].first + b[i].first, nd -= 2, ans.push_back(a[i].second), ans.push_back(b[i].second); for (int i = max(0, k - mid); i < a.size(); i++) vec.push_back(a[i]); for (int i = max(0, k - mid); i < b.size(); i++) vec.push_back(b[i]); for (int i = 0; i < other.size(); i++) vec.push_back(other[i]); sort(vec.begin(), vec.end()); for (int i = 0; i < nd && i < vec.size(); i++) res += vec[i].first, ans.push_back(vec[i].second); return res; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m >> k; for (int i = 1, x1, x2, x3; i <= n; ++i) { cin >> x1 >> x2 >> x3; if (x2 && x3) ab.push_back({x1, i}); else if (x2) a.push_back({x1, i}); else if (x3) b.push_back({x1, i}); else other.push_back({x1, i}); } sort(a.begin(), a.end()), sort(b.begin(), b.end()), sort(ab.begin(), ab.end()), sort(other.begin(), other.end()); int l = 0, r = min((int)ab.size(), m); while (r - l > 10) { int midl = l + (r - l) / 3, midr = r - (r - l) / 3; if (check(midl) >= check(midr)) l = midl; else r = midr; } int res = 2e9 + 1, Min_idx = -1; for (int i = l; i <= r; i++) { int tmp = check(i); if (tmp < res) res = tmp, Min_idx = i; } if (Min_idx == -1) return puts("-1"), 0; cout << check(Min_idx) << endl; for (auto a : ans) cout << a << " "; return 0; }
11
CPP
n,k=map(int,input().split()) x=[] y=[] z=[] for _ in range(n): t,a,b=map(int,input().split()) if(a==1 and b==1): x.append(t) elif(a==1 and b==0): y.append(t) elif(a==0 and b==1): z.append(t) x.sort() y.sort() z.sort() kk=[] p=min(len(y),len(z)) for i in range(p): kk.append(y[i]+z[i]) if(len(kk)+len(x)<k): print(-1) else: i = 0 j = 0 c = [] while (True): if (i == len(kk)): c.extend(x[j:]) break if (j == len(x)): c.extend(kk[i:]) break if (kk[i] > x[j]): c.append(x[j]) j += 1 elif (kk[i] == x[j]): c.append(x[j]) c.append(x[j]) i += 1 j += 1 else: c.append(kk[i]) i += 1 print(sum(c[:k]))
11
PYTHON3
def prefixSum(array): if len(array) == 0: return [] l = [array[0]] for i in array[1:]: l.append(i+l[-1]) return l n, k = 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) continue if a == 1: alice.append(t) if b == 1: bob.append(t) alice.sort() bob.sort() both.sort() if len(alice)+len(both)<k or len(bob)+len(both)<k: print(-1) else: if len(alice) == 0 or len(bob) == 0: s = sum(both[:k]) print(s) else: bothP = prefixSum(both) aliceP = prefixSum(alice) bobP = prefixSum(bob) minTime = 10**18 # If all k are picked from individual if len(alice)>=k and len(bob)>=k: minTime = aliceP[k-1] + bobP[k-1] # If all are picked from both if len(both) >= k: minTime = min(minTime, bothP[k-1]) # If anywhere between 1 to k-1 are picked from both for i in range(1, k): # Remaining k-i books cannot be picked if not (k-i <= len(alice) and k-i <= len(bob)): continue # There are not i books in both if i>len(both): continue # Pick i common rest uncommon elif bothP[i-1] + aliceP[k-i-1] + bobP[k-i-1] < minTime: minTime = bothP[i-1] + aliceP[k-i-1] + bobP[k-i-1] print(minTime)
11
PYTHON3
n, k = [int(x) for x in input().split()] both = [] bob = [] alice = [] for i in range(n): t, a, b = [int(x) for x in input().split()] if(a==1 and b==1): both.append(t) elif(a==1): alice.append(t) elif(b==1): bob.append(t) both.sort() bob.sort() alice.sort() y = max(k-min(len(bob),len(alice)),0) soma_both=0 sa = 0 sb = 0 poss = (len(both)+min(len(alice),len(bob))>=k) if(poss): for i in range(y): soma_both+=both[i] for i in range(max(k-y,0)): sa += alice[i] for i in range(max(k-y,0)): sb += bob[i] ptr1 = k-y ptr2 = k-y resposta = sa+sb+soma_both for i in range(y,len(both)): ptr1-=1 ptr2-=1 if(ptr2==-1 or ptr1==-1): break soma_both+=both[i] sa-=alice[ptr1] sb-=bob[ptr2] if(soma_both+sa+sb>=0): resposta = min(resposta,soma_both+sa+sb) print(resposta) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; long long n, k, t, a, b, it1, it2, score, tim, f, s; vector<long long> vec[4]; int main() { cin >> n >> k; for (int i = 1; i <= n; i++) { cin >> t >> a >> b; if (a == 1) f++; if (b == 1) s++; if (a == 0 && b == 0) continue; if (a == 1 && b == 1) { vec[1].push_back(t); continue; } if (a == 1) vec[2].push_back(t); if (b == 1) vec[3].push_back(t); } if (f < k || s < k) { cout << -1 << endl; } else { for (int i = 1; i <= 3; i++) { sort(vec[i].begin(), vec[i].end()); } it1 = 0; it2 = 0; tim = 0; score = 0; while (score < k) { if (it1 == vec[1].size()) { tim += vec[2][it2] + vec[3][it2]; it2++; score++; continue; } if (it2 == vec[2].size() || it2 == vec[3].size()) { tim += vec[1][it1]; score++; it1++; continue; } if (vec[1][it1] < vec[2][it2] + vec[3][it2]) { tim += vec[1][it1]; score++; it1++; } else { tim += vec[2][it2] + vec[3][it2]; it2++; score++; } } cout << tim << endl; } return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; const int INF = 2147483640; const int MAXN = 2e5 + 5; const int R = 1e4 + 5; int n, m, k; int tot[10]; struct node { int t, i; } A[MAXN], B[MAXN], C[MAXN], D[MAXN], E[MAXN << 2]; bool cmp(node x, node y) { return x.t < y.t; } struct tree { int sum, w; } tr[R << 2]; void modify(int x, int l, int r, int pos, int k) { if (l == r) { tr[x].sum += k * l; tr[x].w += k; return; } int mid = (l + r) / 2; if (pos <= mid) modify(x * 2, l, mid, pos, k); if (pos > mid) modify(x * 2 + 1, mid + 1, r, pos, k); tr[x].sum = tr[x * 2].sum + tr[x * 2 + 1].sum; tr[x].w = tr[x * 2].w + tr[x * 2 + 1].w; } int query(int x, int l, int r, int kth) { int ans = 0; if (kth == tr[x].w) return tr[x].sum; if (l == r) return kth * l; int mid = (l + r) / 2; if (tr[x * 2].w < kth) ans = tr[x * 2].sum + query(x * 2 + 1, mid + 1, r, kth - tr[x * 2].w); else ans = query(x * 2, l, mid, kth); return ans; } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= n; i++) { int t, a, b; scanf("%d%d%d", &t, &a, &b); if (a == 1 && b == 1) A[++tot[1]] = (node){t, i}; if (a == 0 && b == 1) B[++tot[2]] = (node){t, i}; if (a == 1 && b == 0) C[++tot[3]] = (node){t, i}; if (a == 0 && b == 0) D[++tot[4]] = (node){t, i}; } if (min(tot[2], tot[3]) + tot[1] < k) { printf("-1"); return 0; } sort(A + 1, A + tot[1] + 1, cmp); sort(B + 1, B + tot[2] + 1, cmp); sort(C + 1, C + tot[3] + 1, cmp); sort(D + 1, D + tot[4] + 1, cmp); int cost = 0, num = 0; for (int i = 1; i <= min(m, tot[1]); i++) cost += A[i].t, num++; int now = 0; for (int i = 1; i <= k - tot[1]; i++) now++, cost += (B[now].t + C[now].t), num += 2; for (int i = m + 1; i <= tot[1]; i++) modify(1, 1, R, A[i].t, 1); for (int i = now + 1; i <= tot[2]; i++) modify(1, 1, R, B[i].t, 1); for (int i = now + 1; i <= tot[3]; i++) modify(1, 1, R, C[i].t, 1); for (int i = 1; i <= tot[4]; i++) modify(1, 1, R, D[i].t, 1); if (num > m) { printf("-1"); return 0; } int minn = INF, ans_A = 0, ans_B = 0; for (int i = min(m, tot[1]); i >= 0; i--) { if (num > m) break; int ans = cost + query(1, 1, R, m - num); if (ans < minn) minn = ans, ans_A = i, ans_B = now; modify(1, 1, R, A[i].t, 1); cost -= A[i].t; num--; if (now > min(tot[2], tot[3])) break; if (i <= k) { num += 2; now++; if (now > min(tot[2], tot[3])) break; modify(1, 1, R, B[now].t, -1); modify(1, 1, R, C[now].t, -1); cost += (B[now].t + C[now].t); } } int ans = 0; printf("%d\n", minn); for (int i = 1; i <= ans_A; i++) ans += A[i].t; for (int i = 1; i <= ans_B; i++) ans += (B[i].t + C[i].t); int cnt = 0; for (int i = ans_A + 1; i <= min(m, tot[1]); i++) E[++cnt] = A[i]; for (int i = ans_B + 1; i <= tot[2]; i++) E[++cnt] = B[i]; for (int i = ans_B + 1; i <= tot[3]; i++) E[++cnt] = C[i]; for (int i = 1; i <= tot[4]; i++) E[++cnt] = D[i]; sort(E + 1, E + cnt + 1, cmp); for (int i = 1; i <= ans_A; i++) printf("%d ", A[i].i); for (int i = 1; i <= ans_B; i++) printf("%d %d ", B[i].i, C[i].i); for (int i = 1; i <= m - ans_A - ans_B * 2; i++) printf("%d ", E[i].i); return 0; }
11
CPP
n,k=map(int,input().split()) l1=[] #(0,1) l2=[] #(1,0) l3=[] #(1,1) for i in range(n): t,a,b=map(int,input().split()) if (a,b)==(1,1): l3.append(t) elif (a,b)==(0,1): l1.append(t) elif (a,b)==(1,0): l2.append(t) s=0 l1.sort() l2.sort() l3.sort() if len(l3)>=k: s=sum(l3[:k]) p=0 p1=k-1 else: s=sum(l3) v=k-len(l3) if len(l1)>=v and len(l2)>=v: s+=sum(l1[:v])+sum(l2[:v]) else: print(-1) exit() p=v p1=len(l3)-1 while(p<len(l1) and p<len(l2) and p1>=0): if l1[p]+l2[p]<=l3[p1]: s=s-l3[p1]+l1[p]+l2[p] p1-=1 p+=1 else: break print(s)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; template <typename T> void print1d(vector<T> &a) { for (long long int i = 0; i < a.size(); i++) { cout << a[i] << " "; } cout << endl; } vector<long long int> divisor(long long int n) { vector<long long int> a; for (long long int i = 1; i * i <= n; i++) { if (n % i == 0) { if (n / i == i) a.push_back(i); else { a.push_back(i); a.push_back(n / i); } } } return a; } long long int K = 1E9; bool sortsecond(const pair<long long int, long long int> &a, const pair<long long int, long long int> &b) { return a.second < b.second; } bool sortmake(const pair<long long int, long long int> &a, const pair<long long int, long long int> &b) { if (a.first < b.first) return true; else if (a.first > b.first) return false; else { if (a.second < b.second) return false; else return true; } } bool isPrime(long long int n) { for (long long int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } int32_t main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); ; long long int n, k; cin >> n >> k; vector<long long int> a, b, c; long long int x, y, z; for (long long int i = 0; i < n; i++) { cin >> x >> y >> z; if (y == 1 && z == 1) a.push_back(x); else if (y == 1) b.push_back(x); else if (z == 1) c.push_back(x); } long long int an = a.size(); long long int bn = b.size(); long long int cn = c.size(); if (an + min(bn, cn) < k) { cout << -1 << endl; return 0; } sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(c.begin(), c.end()); long long int dn = min(bn, cn); long long int ans = 0; long long int i = 0, j = 0; for (long long int q = 0; q < k; q++) { if (i < an && j < dn) { if (a[i] <= b[j] + c[j]) { ans += a[i]; i++; } else { ans += b[j] + c[j]; j++; } } else if (i >= an) { ans += b[j] + c[j]; j++; } else if (j >= dn) { ans += a[i]; i++; } } cout << ans << endl; return 0; }
11
CPP
#------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') 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") def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# #vsInput() n,k=value() alice=[] bob=[] both=[] for i in range(n): t,a,b=value() 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() #print(alice) #print(bob) #print(both) #print() ans=0 if(len(bob)+len(both)<k or len(alice)+len(both)<k): print(-1) exit() if(len(alice)<k): dif=k-len(alice) ans+=sum(both[:dif]) both=both[dif:] k-=dif if(len(bob)<k): dif=k-len(bob) ans+=sum(both[:dif]) both=both[dif:] k-=dif #print(alice) #print(bob) #print(both) #print() a=0 b=0 bo=0 for i in range(k): if(bo<len(both) and alice[a]+bob[b]>both[bo]): ans+=both[bo] bo+=1 else: ans+=alice[a]+bob[b] a+=1 b+=1 print(ans)
11
PYTHON3
# cook your dish here #code import math import collections from sys import stdin,stdout,setrecursionlimit from bisect import bisect_left as bsl from bisect import bisect_right as bsr import heapq as hq setrecursionlimit(2**20) T = 1 #T = int(stdin.readline()) for _ in range(T): #n = int(stdin.readline()) n,k = list(map(int, stdin.readline().rstrip().split())) t,a,b = [],[],[] sa,sb = 0,0 for i in range(n): t1,t2,t3 = list(map(int, stdin.readline().rstrip().split())) t.append(t1) a.append(t2) b.append(t3) sa += t2 sb += t3 if(sa<k or sb<k): print(-1) continue else: on_a = [] on_b = [] on_ab = [] for i in range(n): if(a[i]==1 and b[i]==1): on_ab.append(t[i]) elif(a[i]==1): on_a.append(t[i]) elif(b[i]==1): on_b.append(t[i]) on_a.sort() on_b.sort() on_ab.sort() ans = 0 ai, bi, abi = 0,0,0 cnta, cntb = 0,0 while((cnta!=k and cntb!=k) and (ai<len(on_a) and bi<len(on_b) and abi<len(on_ab)) ): if(on_a[ai]+on_b[bi]<on_ab[abi]): cnta += 1 cntb += 1 ans += (on_a[ai] + on_b[bi]) ai += 1 bi += 1 else: cnta += 1 cntb += 1 ans += on_ab[abi] abi += 1 if(cnta==k): print(ans) continue elif(abi<len(on_ab)): while(cnta!=k): ans += on_ab[abi] abi += 1 cnta+=1 print(ans) continue else: while(cnta!=k): ans += on_a[ai] ai += 1 cnta+=1 while(cntb!=k): ans += on_b[bi] bi += 1 cntb+=1 print(ans) continue
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, k; struct Book { int t, a, b; bool operator<(const Book &w) const { return t < w.t; } } books[N]; vector<int> a, b; bool st[N]; int main() { cin >> n >> k; for (int i = 0; i < n; i++) { cin >> books[i].t >> books[i].a >> books[i].b; } sort(books, books + n); int cnta = 0, cntb = 0; for (int i = 0; i < n; i++) { int t = books[i].t, x = books[i].a, y = books[i].b; if (!x && !y) { continue; } else if (x && y) { if (cnta < k && cntb < k) { cnta++, cntb++; st[i] = true; } else if (cnta < k && cntb >= k) { cnta++; st[i] = true; int c = b[b.size() - 1]; b.pop_back(); st[c] = false; } else if (cnta >= k && cntb < k) { cntb++; st[i] = true; int c = a[a.size() - 1]; a.pop_back(); st[c] = false; } else { if (!a.size() || !b.size()) { break; } int t1 = books[a[a.size() - 1]].t, t2 = books[b[b.size() - 1]].t; if (t < t1 + t2) { st[i] = true; int c = b[b.size() - 1]; b.pop_back(); st[c] = false; c = a[a.size() - 1]; a.pop_back(); st[c] = false; } else { break; } } } else if (x && !y && cnta < k) { cnta++; a.push_back(i); st[i] = true; } else if (!x && y && cntb < k) { cntb++; b.push_back(i); st[i] = true; } } if (cnta < k || cntb < k) { cout << -1 << endl; } else { int res = 0; for (int i = 0; i < n; i++) { if (st[i]) { res += books[i].t; } } cout << res << endl; } return 0; }
11
CPP
from heapq import heappush, heappop from sys import stdin, stdout # if __name__ == '__main__': def reading_books(n, k, ta, tb, tab): res = 0 for i in range(k): if len(tab) == 0 and (len(ta) == 0 or len(tb) == 0): return -1 t1 = 100000 t2 = 100000 t3 = 100000 if len(tab) > 0: t1 = tab[0] if len(ta) > 0: t2 = ta[0] if len(tb) > 0: t3 = tb[0] if t1 <= t2+t3: res += heappop(tab) else: res += heappop(ta) + heappop(tb) return res n, k = map(int, stdin.readline().split()) ta = [] tb = [] tab = [] for i in range(n): t, a, b = map(int, stdin.readline().split()) if a == 1 and b == 1: heappush(tab, t) elif a == 1: heappush(ta, t) elif b == 1: heappush(tb, t) res = reading_books(n, k, ta, tb, tab) stdout.write(str(res) + '\n');
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { long long int n, m; cin >> n >> m; vector<long long int> aa, bb, cc; vector<long long int> a(n + 5); vector<long long int> b(n + 5); vector<long long int> c(n + 5); for (long long int i = 1; i <= n; i++) { cin >> a[i] >> b[i] >> c[i]; if (b[i] && c[i]) cc.push_back(a[i]); else if (b[i]) aa.push_back(a[i]); else if (c[i]) bb.push_back(a[i]); } sort(aa.begin(), aa.end()); sort(bb.begin(), bb.end()); sort(cc.begin(), cc.end()); vector<long long int> vc1(n + 5), vc2(n + 5); for (long long int i = 0; i <= (long long int)aa.size() - 1; i++) { if (!i) { int gg = 0; } else { vc1[i] = vc1[i - 1]; } vc1[i] += aa[i]; } for (long long int j = 0; j <= (long long int)bb.size() - 1; j++) { if (!j) { int hh = 0; } else { vc2[j] = vc2[j - 1]; } vc2[j] += bb[j]; } long long int mxx = INT_MAX, s = 0; for (long long int k = 0; k <= cc.size(); k++) { if (!k) { int hg = 0; } else { m--; s += cc[k - 1]; } if (aa.size() < m) { continue; } if (bb.size() < m) { continue; } if (m > 0) { mxx = min(mxx, s + vc1[m - 1] + vc2[m - 1]); } else mxx = min(mxx, s); } if (mxx != INT_MAX) { int yy = 0; } else mxx = -1; cout << mxx << endl; }
11
CPP
from sys import stdin, stdout import math from collections import defaultdict, deque n, k = map(int, stdin.readline().split()) al, bl, both = [], [], [] for _ in range(n): t, a, b = map(int, stdin.readline().split()) if a == 0 and b == 0: continue if a == 1 and b == 1: both.append(t) elif a == 1: al.append(t) elif b == 1: bl.append(t) al, bl, both = deque(sorted(al)[:k]), deque(sorted(bl)[:k]), deque(sorted(both)[:k]) res, cnt = 0, 0 while cnt < k: if both: if al and bl: if both[0] < al[0]+bl[0]: res += both[0] both.popleft() cnt += 1 else: res += al[0]+bl[0] al.popleft() bl.popleft() cnt += 1 else: res += both[0] both.popleft() cnt += 1 else: if al and bl: res += al[0]+bl[0] al.popleft() bl.popleft() cnt += 1 else: res = -1 break print(res)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << "{"; for (typename vector<T>::const_iterator vi = v.begin(); vi != v.end(); ++vi) { if (vi != v.begin()) os << ", "; os << *vi; } os << "}"; return os; } template <typename A, typename B> ostream &operator<<(ostream &os, const pair<A, B> &p) { os << '(' << p.first << ", " << p.second << ')'; return os; } mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); long long T, N, M, K; long long qtd11, minAns; vector<pair<int, int> > v[4]; int nums[200010]; int menor(vector<int> &ptr) { pair<int, int> ans(0x3f3f3f3f, 0x3f3f3f3f); int pos = -1; for (int i = 0; i < 4; i++) { if (ptr[i] < v[i].size() && ans >= v[i][ptr[i]]) { ans = v[i][ptr[i]]; pos = i; } } return pos; } void imp() { cout << -1 << "\n"; exit(0); } pair<int, int> p(pair<int, int> a) { return pair<int, int>(-a.first, -a.second); } void melhor() { for (int i = 0; i < 4; i++) sort(v[i].begin(), v[i].end()); vector<pair<int, int> > resp[4]; vector<int> ptr(4, 0); long long ans = 0, l11 = max(0LL, 2 * M - K), l01; l01 = M - l11; if (v[0].size() < l11) imp(); for (; ptr[0] < l11; ptr[0]++) { resp[0].push_back(v[0][ptr[0]]); ans += v[0][ptr[0]].first; } while (ptr[0] < v[0].size() && (v[1].size() < l01 || v[2].size() < l01)) { l01--; resp[0].push_back(v[0][ptr[0]]); ans += v[0][ptr[0]].first; ptr[0]++; } while (ptr[0] < v[0].size() && ptr[0] + v[1].size() + v[2].size() + v[3].size() < K) { l01--; resp[0].push_back(v[0][ptr[0]]); ans += v[0][ptr[0]].first; ptr[0]++; } if (v[1].size() < l01 || v[2].size() < l01) imp(); for (; ptr[1] < l01; ptr[1]++, ptr[2]++) { resp[1].push_back(v[1][ptr[1]]); resp[2].push_back(v[2][ptr[2]]); ans += v[1][ptr[1]].first; ans += v[2][ptr[2]].first; } priority_queue<pair<int, int> > sob, others; for (int i = 1; i < 4; i++) { for (int j = ptr[i]; j < v[i].size(); j++) { sob.push(p(v[i][j])); } } while (!sob.empty() && ptr[0] + ptr[1] + ptr[2] + others.size() < K) { ans += -sob.top().first; others.push(p(sob.top())); sob.pop(); } minAns = ans; qtd11 = ptr[0]; for (; ptr[1] && ptr[0] < v[0].size(); ptr[0]++) { ptr[1]--, ptr[2]--; sob.push(p(resp[1][ptr[1]])); ans -= resp[1][ptr[1]].first; resp[1].pop_back(); sob.push(p(resp[2][ptr[2]])); ans -= resp[2][ptr[2]].first; resp[2].pop_back(); resp[0].push_back(v[0][ptr[0]]); ans += v[0][ptr[0]].first; pair<int, int> u = p(sob.top()); sob.pop(); others.push(u); ans += u.first; while (others.top() > p(sob.top())) { pair<int, int> aux = others.top(); pair<int, int> aux2 = p(sob.top()); ans -= aux.first; ans += aux2.first; others.pop(); sob.pop(); others.push(aux2); sob.push(p(aux)); } if (ans < minAns) { qtd11 = resp[0].size(); minAns = ans; } } } void construir() { vector<pair<int, int> > resp; vector<int> ptr(4, 0); long long ans = 0; for (; ptr[0] < qtd11; ptr[0]++) { resp.push_back(v[0][ptr[0]]); ans += v[0][ptr[0]].first; } for (int i = qtd11; i < M; i++, ptr[1]++, ptr[2]++) { resp.push_back(v[1][ptr[1]]); resp.push_back(v[2][ptr[2]]); ans += v[1][ptr[1]].first; ans += v[2][ptr[2]].first; } while (resp.size() < K) { int pos = menor(ptr); ans += v[pos][ptr[pos]].first; resp.push_back(v[pos][ptr[pos]]); ptr[pos]++; } cout << ans << "\n"; for (int i = 0; i < resp.size(); i++) { if (!i) cout << resp[i].second + 1; else cout << " " << resp[i].second + 1; } cout << "\n"; } void solve() { melhor(); construir(); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; cin >> N >> K >> M; for (int i = 0; i < N; i++) { int a, b, t; cin >> t >> a >> b; if (a && b) { v[0].push_back(pair<int, int>(t, i)); } else if (a) { v[1].push_back(pair<int, int>(t, i)); } else if (b) { v[2].push_back(pair<int, int>(t, i)); } else { v[3].push_back(pair<int, int>(t, i)); } nums[i] = t; } solve(); return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } long long lcm(long long a, long long b) { return (a * b) / gcd(a, b); } void print(vector<long long> a) { for (int i = 0; i < a.size(); i++) { cout << a[i] << ' '; } cout << endl; } vector<long long> inp(int n) { vector<long long> a; long long x; for (int i = 0; i < n; i++) { cin >> x; a.push_back(x); } return a; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long t, n, i, j, k, l, c1, cnt, flag, m1, m, m2, maxi, mini, x, y, z; vector<long long> a, b, c; string s, s1, s2; cin >> n >> k; for (i = 0; i < n; i++) { cin >> x >> y >> z; if (y + z == 2) { c.push_back(x); } else { if (y == 1) { a.push_back(x); } if (z == 1) { b.push_back(x); } } } sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(c.begin(), c.end()); cnt = 0; if (c.size() + a.size() >= k && c.size() + b.size() >= k) { i = 0, j = 0, l = 0; while (i != k) { if (j < a.size() && j < b.size()) { if (l < c.size()) { if (a[j] + b[j] < c[l]) { cnt = cnt + a[j] + b[j]; j++; } else { cnt = cnt + c[l]; l++; } } else { cnt = cnt + a[j] + b[j]; j++; } } else { cnt = cnt + c[l]; l++; } i++; } cout << cnt << endl; } else { cout << -1 << endl; } }
11
CPP
import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction # import numpy as np sys.setrecursionlimit(int(pow(10,6))) # sys.stdin = open("input.txt", "r") # sys.stdout = open("out.txt", "w") mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] # @lru_cache(None) t=1 # t=int(input()) for _ in range(t): n,k=l() A=[[],[],[]] bc=0 ac=0 for i in range(n): a,b,c=l() if b==c and b==1: A[0].append(a) elif b==1 and c==0: A[1].append(a) elif b==0 and c==1: A[2].append(a) A[0].sort() A[1].sort() A[2].sort() for i in range(1,len(A[0])): A[0][i]+=A[0][i-1] for i in range(1,len(A[1])): A[1][i]+=A[1][i-1] for i in range(1,len(A[2])): A[2][i]+=A[2][i-1] time=10**10 A[0]=[0]+A[0] A[1]=[0]+A[1] A[2]=[0]+A[2] # print(*A) for cnt in range(len(A[0])): try: time=min(time,A[0][cnt]+A[1][k-cnt]+A[2][k-cnt]) # print(cnt,time) except: continue if time==10**10: print(-1) else: print(time)
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[ib] ib += 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
def main(): n, k = [int(x) for x in input().split()] alice, bob = 0, 0 both, j_a, j_b = [], [], [] for i in range(n): b = [int(x) for x in input().split()] if(b[1] + b[2] == 2): both.append(b) elif (b[1] == 1): j_a.append(b) elif(b[2] == 1): j_b.append(b) j_a.sort() j_b.sort() for i in range(min(len(j_a), len(j_b))): b = [j_a[i][0] + j_b[i][0], 1, 1] both.append(b) if(len(both) < k): return -1 both.sort() return sum([b[0] for b in both[:k]]) print(main())
11
PYTHON3
from collections import deque from operator import itemgetter from sys import stdin, stdout int_in = lambda: int(stdin.readline()) arr_in = lambda: [int(x) for x in stdin.readline().split()] mat_in = lambda rows: [arr_in() for _ in range(rows)] str_in = lambda: stdin.readline().strip() out = lambda o: stdout.write("{}\n".format(o)) arr_out = lambda o: out(" ".join(map(str, o))) bool_out = lambda o: out("YES" if o else "NO") tests = lambda: range(1, int_in() + 1) case_out = lambda i, o: out("Case #{}: {}".format(i, o)) def solve(n, k, books): alice_books = list(sorted(filter(lambda x: x[1] == 1 and x[2] == 0, books), key=itemgetter(0)))[:k] bob_books = list(sorted(filter(lambda x: x[1] == 0 and x[2] == 1, books), key=itemgetter(0)))[:k] shared_books = list(sorted(filter(lambda x: x[1] == 1 and x[2] == 1, books), key=itemgetter(0)))[:k] have = min(len(alice_books), len(bob_books)) need = k - have using_shared_books = [] if need > 0: if len(shared_books) < need: return -1 alice_books = alice_books[:have] bob_books = bob_books[:have] using_shared_books = shared_books[:need] shared_books = shared_books[need:] shared_books = deque(shared_books) if have > 0: while len(alice_books) > 0 and len(bob_books) > 0 and len(shared_books) > 0 and alice_books[-1][0] + bob_books[-1][0] > shared_books[0][0]: using_shared_books.append(shared_books[0]) alice_books.pop() bob_books.pop() shared_books.popleft() if len(alice_books) + len(using_shared_books) != k: return -1 if len(bob_books) + len(using_shared_books) != k: return -1 result = 0 for item in alice_books: result += item[0] for item in bob_books: result += item[0] for item in using_shared_books: result += item[0] return result if __name__ == "__main__": n, k = arr_in() books = mat_in(n) out(solve(n, k, books))
11
PYTHON3
# cook your dish here n,k=map(int,input().split()) a=[] b=[] bb=[] x=[] cnta=0 cntb=0 for i in range(n): t,p,q=list(map(int,input().split())) t=[t,p,q] x.append(t) t,p,q=x[i] if p and q: bb.append(t) cnta+=1 cntb+=1 elif p: a.append(t) cnta+=1 elif q: b.append(t) cntb+=1 a.sort() b.sort() if cnta>=k and cntb>=k: for i in range(min(len(a),len(b))): bb.append(a[i]+b[i]) out=0 bb.sort() for i in range(k): out+=bb[i] print(out) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; void test_case() { long long int n, k; cin >> n >> k; vector<long long int> as, bs, cs; for (long long int i = 0; i < n; i++) { long long int t, a, b; cin >> t >> a >> b; if (a + b == 2) cs.push_back(t); else if (a == 1) as.push_back(t); else if (b == 1) bs.push_back(t); } if (as.size() + cs.size() < k) { cout << -1; return; } if (bs.size() + cs.size() < k) { cout << -1; return; } sort(as.begin(), as.end()); sort(bs.begin(), bs.end()); sort(cs.begin(), cs.end()); long long int a, b, c, done = 0, res = 0; a = b = c = 0; while (c < cs.size() && c < k) res += cs[c++]; while (a + c < k) res += as[a++]; while (b + c < k) res += bs[b++]; while (a < as.size() && b < bs.size() && c > 0 && as[a] + bs[b] <= cs[c - 1]) res += (as[a++] + bs[b++] - cs[--c]); cout << res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int t = 1; for (long long int i = 0; i < t; i++) { test_case(); cout << endl; } return 0; }
11
CPP
arr=[int(x) for x in input().split()] size=arr[0] total=arr[1] book_dict={'2':[],'10':[],'01':[]} for i in range(size): book_arr=[int(x) for x in input().split()] if book_arr[1]==1 and book_arr[2]==1: book_dict['2'].append(book_arr[0]) elif book_arr[1]==1 and book_arr[2]==0: book_dict['10'].append(book_arr[0]) elif book_arr[1]==0 and book_arr[2]==1: book_dict['01'].append(book_arr[0]) count10=len(book_dict['10']) count01=len(book_dict['01']) count2=len(book_dict['2']) result=0 book_dict['10'].sort() book_dict['01'].sort() if count10+count2>=total and count01+count2>=total: for i in range(min(count01,count10)): book_dict['2'].append(book_dict['01'][i]+book_dict['10'][i]) book_dict['2'].sort() result=sum(book_dict['2'][:total]) print(result) else: print(-1)
11
PYTHON3
def p(x): return x[0] n, k = map(int, input().split()) a = [] for i in range(n): a.append(list(map(int, input().split()))) a.sort(key=p) # print() # print() # for i in a: # print(i) alice, bob, common = [], [], [] al, bo = 0, 0 flag = 1 for i in a: if(i[1] and not i[2] and al < k): alice.append(i[0]) al += 1 if(i[2] and (not i[1]) and bo < k): bob.append(i[0]) bo += 1 if(i[1] and i[2]): if(al<k or bo<k): common.append(i[0]) al += 1 bo += 1 if(al > k ): alice.pop() al -= 1 if(bo > k): bob.pop() bo -= 1 else: if(alice and bob): if(alice[-1]+bob[-1] > i[0]): alice.pop() bob.pop() common.append(i[0]) else: break # print(alice, bob, common, al, bo) if(al >= k and bo >= k): print(sum(alice)+sum(bob)+sum(common)) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; long long inf = 1e9; signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long n, k; cin >> n >> k; vector<long long> l; vector<long long> m; vector<long long> r; for (long long i = 0; i < n; ++i) { long long a, b, c; cin >> a >> b >> c; if (b == 1 && c == 1) { m.push_back(a); } else if (b == 1 && c == 0) { l.push_back(a); } else if (b == 0 && c == 1) { r.push_back(a); } } sort(l.begin(), l.end()); sort(r.begin(), r.end()); sort(m.begin(), m.end()); auto it1 = l.begin(); auto it2 = m.begin(); auto it3 = r.begin(); long long ans = 0; long long x = 0, y = 0; while ((x < k && y < k) && (((it1 != l.end()) && (it3 != r.end())) || (it2 != m.end()))) { if ((it2 == m.end()) || (it1 != l.end() && it3 != r.end() && *it1 + *it3 < *it2)) { ans += (*it1 + *it3); it1++; it3++; } else if ((it2 != m.end()) || ((it1 == l.end() || (it3 == r.end())))) { ans += *it2; it2++; } x++; y++; } if (x == k && y == k) cout << ans << "\n"; else cout << -1 << "\n"; }
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 = deque(sorted(bob)) alice = deque(sorted(alice)) both = deque(sorted(both)) ans = 0 while k: try: X = both[0] except: X = float('inf') try: A = alice[0] except: A = float('inf') try: B = bob[0] except: B = float('inf') # print(alice, bob, both) # print(A, B, X) if (A == float('inf')) or (B == float('inf')): ans += X both.popleft() elif X == float('inf'): ans += A + B alice.popleft() bob.popleft() elif A + B < X: ans += A + B alice.popleft() bob.popleft() else: ans += X both.popleft() 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()) alice = [] bob=[] comm=[] for _ in range(n): a,b,c=map(int,input().split()) if(b==1 and c==1): comm.append(a) elif(b==1 and c==0): alice.append(a) elif(b==0 and c==1): bob.append(a) alice.sort() bob.sort() for i in range(min(len(alice),len(bob))): comm.append(alice[i]+bob[i]) comm.sort() if(len(comm) < k): print(-1) else: print(sum(comm[:k]))
11
PYTHON3
from sys import stdin from collections import defaultdict as dd from collections import deque as dq import itertools as it from math import sqrt, log, log2 from fractions import Fraction n, k = map(int, input().split()) alike, blike = 0, 0 zero_one, one_zero, one_one, zero_zero = [], [], [], [] for i in range(n): t, a, b = map(int, input().split()) alike += a blike += b if a == 0 and b == 1: zero_one.append((t, i)) elif a == 1 and b == 0: one_zero.append((t, i)) elif a== 1 and b== 1: one_one.append((t, i)) else: pass # zero_zero.append((t, i)) if alike < k or blike < k: print(-1) exit() zero_one.sort(key = lambda x: x[0]) one_one.sort(key = lambda x: x[0]) one_zero.sort(key = lambda x: x[0]) # zero_zero.sort(key = lambda x: x[0]) alike, blike = 0, 0 zo, oo, oz, zz = 0, 0, 0, 0 lzo, loo, loz = len(zero_one), len(one_one), len(one_zero) # lzo, loo, loz, lzz = len(zero_one), len(one_one), len(one_zero), len(zero_zero) tottime = 0 while alike<k or blike<k: # if oo >= loo and zo >= lzo and oz>=loz: # break # lbo = len(books) # if lbo == m: if alike <k and blike <k: if oo>= loo and zo>=lzo and oz>=loz: print(-1) exit() elif zo >= lzo or oz >= loz: tottime += one_one[oo][0] # books.append(one_one[oo][1]) oo += 1 elif oo >= loo: tottime += zero_one[zo][0] + one_zero[oz][0] # books.append(zero_one[zo][1]) # books.append(zero_one[oz][1]) zo += 1 oz += 1 elif zero_one[zo][0] + one_zero[oz][0] < one_one[oo][0]: tottime += zero_one[zo][0] + one_zero[oz][0] # books.append(zero_one[zo][1]) # books.append(zero_one[oz][1]) zo += 1 oz += 1 else: tottime += one_one[oo][0] # books.append(one_one[oo][1]) oo += 1 alike += 1 blike += 1 elif alike == k and blike < k: if oo>=loo and zo>=lzo: print(-1) exit() elif oo >= loo: tottime += zero_one[zo][0] # books.append(zero_one[zo][1]) zo += 1 elif zo >= lzo: tottime += one_one[oo][0] # books.append(one_one[oo][1]) oo += 1 elif zero_one[zo][0] < one_one[oo][0]: tottime += zero_one[zo][0] # books.append(zero_one[zo][1]) zo += 1 else: tottime += one_one[oo][0] # books.append(one_one[oo][1]) oo += 1 blike += 1 elif alike <k and blike == k: if oo>=loo and oz>=loz: print(-1) exit() elif oo>=loo: tottime += one_zero[oz][0] # books.append(one_zero[oz][1]) oz += 1 elif oz>= loz: tottime += one_one[oo][0] # books.append(one_one[oo][1]) oo += 1 elif one_zero[oz][0] < one_one[oo][0]: tottime += one_zero[oz][0] # books.append(one_zero[oz][1]) oz += 1 else: tottime += one_one[oo][0] # books.append(one_one[oo][1]) oo += 1 print(tottime) # print(*books)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; long long mod = 1000000007; long long dx[] = {1, -1, 0, 0}; long long dy[] = {0, 0, 1, -1}; void solve() { long long n, k; cin >> n >> k; vector<long long> arr1, arr2, v; for (long long i = 0; i < n; i++) { long long x, a, b; cin >> x >> a >> b; if (a && b) v.push_back(x); else if (a) arr1.push_back(x); else if (b) arr2.push_back(x); } sort((arr1).begin(), (arr1).end()); sort((arr2).begin(), (arr2).end()); for (long long i = 0; i < min(arr1.size(), arr2.size()); i++) v.push_back(arr1[i] + arr2[i]); sort((v).begin(), (v).end()); if (v.size() < k) cout << -1 << '\n'; else { long long ans = 0; for (long long i = 0; i < k; i++) ans += v[i]; cout << ans << '\n'; } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long test; test = 1; long long x = 1; while (test--) { solve(); } return 0; }
11
CPP
n,k = [int(x) for x in input().split()] books=[] books_a=[] books_b=[] for i in range(n): b = [int(x) for x in input().split()] if b[1]==1 and b[2]==1: books.append(b[0]) elif b[1]==1: books_a.append(b[0]) elif b[2]==1: books_b.append(b[0]) books_a=sorted(books_a) books_b=sorted(books_b) z= min(len(books_a) , len(books_b)) for j in range(z): books.append(books_a[j] + books_b[j]) books=sorted(books) ans=0 if len(books) < k: print(-1) else: for f in range(k): ans+=books[f] print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const int MAX_INT = numeric_limits<int>::max(); const int MAX_UINT = numeric_limits<unsigned int>::max(); void get_acum(const vector<int>& v, vector<int>& acum) { int sum = 0; for (unsigned int i = 0; i < v.size(); ++i) { acum.push_back(sum); sum += v[i]; } acum.push_back(sum); } int solve(vector<int>& A, vector<int>& B, vector<int>& X, unsigned int k) { if (A.size() + X.size() < k || B.size() + X.size() < k) { return -1; } else { sort(A.begin(), A.end()); sort(B.begin(), B.end()); sort(X.begin(), X.end()); vector<int> A_acum, B_acum, X_acum; get_acum(A, A_acum); get_acum(B, B_acum); get_acum(X, X_acum); int res = MAX_INT; unsigned int max_i = min((unsigned int)X.size(), k); for (unsigned int i = 0; i < max_i + 1; ++i) { if (k - i < A_acum.size() && k - i < B_acum.size()) { int total = A_acum[k - i] + B_acum[k - i] + X_acum[i]; if (total < res) res = total; } } return res; } } int main() { ios::sync_with_stdio(false); cin.tie(NULL); unsigned int n, k; cin >> n >> k; vector<int> A; vector<int> B; vector<int> X; for (unsigned int i = 0; i < n; ++i) { unsigned int ti; bool ai, bi; cin >> ti >> ai >> bi; if (ai && bi) X.push_back(ti); else if (ai) A.push_back(ti); else if (bi) B.push_back(ti); } cout << solve(A, B, X, k); return 0; }
11
CPP
#### IMPORTANT LIBRARY #### ############################ ### DO NOT USE import random --> 250ms to load the library ############################ ### In case of extra libraries: https://github.com/cheran-senthil/PyRival ###################### ####### IMPORT ####### ###################### from functools import cmp_to_key from collections import deque from heapq import heappush, heappop from math import log, ceil ###################### #### STANDARD I/O #### ###################### import sys import os from io import BytesIO, IOBase 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") if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def print(*args, **kwargs): sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def ii(): return int(inp()) def li(lag = 0): l = list(map(int, inp().split())) if lag != 0: for i in range(len(l)): l[i] += lag return l def mi(lag = 0): matrix = list() for i in range(n): matrix.append(li(lag)) return matrix def sli(): #string list return list(map(str, inp().split())) def print_list(lista, space = " "): print(space.join(map(str, lista))) ###################### ##### UNION FIND ##### ###################### class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n def find(self, a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self, a, b): a = self.find(a) b = self.find(b) if a == b: return if self.size[a] < self.size[b]: a, b = b, a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets ###################### ### BISECT METHODS ### ###################### def bisect_left(a, x): """i tale che a[i] >= x e a[i-1] < x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] < x: left = mid+1 else: right = mid return left def bisect_right(a, x): """i tale che a[i] > x e a[i-1] <= x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] > x: right = mid else: left = mid+1 return left def bisect_elements(a, x): """elementi pari a x nell'árray sortato""" return bisect_right(a, x) - bisect_left(a, x) ###################### #### CUSTOM SORT ##### ###################### def custom_sort(lista): def cmp(x,y): if x+y>y+x: return 1 else: return -1 return sorted(lista, key = cmp_to_key(cmp)) ###################### ### MOD OPERATION #### ###################### MOD = 10**9 + 7 maxN = 10**5 FACT = [0] * maxN def add(x, y): return (x+y) % MOD def multiply(x, y): return (x*y) % MOD def power(x, y): if y == 0: return 1 elif y % 2: return multiply(x, power(x, y-1)) else: a = power(x, y//2) return multiply(a, a) def inverse(x): return power(x, MOD-2) def divide(x, y): return multiply(x, inverse(y)) def allFactorials(): FACT[0] = 1 for i in range(1, maxN): FACT[i] = multiply(i, FACT[i-1]) def coeffBinom(n, k): if n < k: return 0 return divide(FACT[n], multiply(FACT[k], FACT[n-k])) ###################### #### GCD & PRIMES #### ###################### def primes(N): smallest_prime = [1] * (N+1) prime = [] smallest_prime[0] = 0 smallest_prime[1] = 0 for i in range(2, N+1): if smallest_prime[i] == 1: prime.append(i) smallest_prime[i] = i j = 0 while (j < len(prime) and i * prime[j] <= N): smallest_prime[i * prime[j]] = min(prime[j], smallest_prime[i]) j += 1 return prime, smallest_prime def gcd(a, b): a = abs(a) b = abs(b) s, t, r = 0, 1, b old_s, old_t, old_r = 1, 0, a while r != 0: quotient = old_r//r old_r, r = r, old_r - quotient*r old_s, s = s, old_s - quotient*s old_t, t = t, old_t - quotient*t return old_r, old_s, old_t #gcd, x, y for ax+by=gcd ###################### #### GRAPH ALGOS ##### ###################### # ZERO BASED GRAPH def create_graph(n, m, undirected = 1, unweighted = 1): graph = [[] for i in range(n)] if unweighted: for i in range(m): [x, y] = li(lag = -1) graph[x].append(y) if undirected: graph[y].append(x) else: for i in range(m): [x, y, w] = li(lag = -1) w += 1 graph[x].append([y,w]) if undirected: graph[y].append([x,w]) return graph def create_tree(n, unweighted = 1): children = [[] for i in range(n)] if unweighted: for i in range(n-1): [x, y] = li(lag = -1) children[x].append(y) children[y].append(x) else: for i in range(n-1): [x, y, w] = li(lag = -1) w += 1 children[x].append([y, w]) children[y].append([x, w]) return children def create_edges(m, unweighted = 0): edges = list() if unweighted: for i in range(m): edges.append(li(lag = -1)) else: for i in range(m): [x, y, w] = li(lag = -1) w += 1 edges.append([w,x,y]) return edges def dist(tree, n, A, B = -1): s = [[A, 0]] massimo, massimo_nodo = 0, 0 distanza = -1 v = [-1] * n while s: el, dis = s.pop() if dis > massimo: massimo = dis massimo_nodo = el if el == B: distanza = dis for child in tree[el]: if v[child] == -1: v[child] = 1 s.append([child, dis+1]) return massimo, massimo_nodo, distanza def diameter(tree): _, foglia, _ = dist(tree, n, 0) diam, _, _ = dist(tree, n, foglia) return diam def dfs(graph, n, A): v = [-1] * n s = [[A, 0]] v[A] = 0 while s: el, dis = s.pop() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges def bfs(graph, n, A): v = [-1] * n s = deque() s.append([A, 0]) v[A] = 0 while s: el, dis = s.popleft() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges def connected(graph, n): v = dfs(graph, n, 0) for el in v: if el == -1: return False return True # NON DIMENTICARTI DI PRENDERE GRAPH COME DIRETTO def topological(graph, n): indegree = [0] * n for el in range(n): for child in graph[el]: indegree[child] += 1 s = deque() for el in range(n): if indegree[el] == 0: s.append(el) order = [] while s: el = s.popleft() order.append(el) for child in graph[el]: indegree[child] -= 1 if indegree[child] == 0: s.append(child) if n == len(order): return False, order #False == no cycle else: return True, [] #True == there is a cycle and order is useless # ASSUMING CONNECTED def bipartite(graph, n): color = [-1] * n color[0] = 0 s = [0] while s: el = s.pop() for child in graph[el]: if color[child] == color[el]: return False if color[child] == -1: s.append(child) color[child] = 1 - color[el] return True # SHOULD BE DIRECTED AND WEIGHTED def dijkstra(graph, n, A): dist = [float('inf') for i in range(n)] prev = [-1 for i in range(n)] dist[A] = 0 pq = [] heappush(pq, [0, A]) while pq: [d_v, v] = heappop(pq) if (d_v != dist[v]): continue for to, w in graph[v]: if dist[v] + w < dist[to]: dist[to] = dist[v] + w prev[to] = v heappush(pq, [dist[to], to]) return dist, prev # SHOULD BE DIRECTED AND WEIGHTED def dijkstra_0_1(graph, n, A): dist = [float('inf') for i in range(n)] dist[A] = 0 p = deque() p.append(A) while p: v = p.popleft() for to, w in graph[v]: if dist[v] + w < dist[to]: dist[to] = dist[v] + w if w == 1: q.append(to) else: q.appendleft(to) return dist #SHOULD BE WEIGHTED (AND UNDIRECTED) def floyd_warshall(graph, n): dist = [[float('inf') for _ in range(n)] for _ in range(n)] for i in range(n): dist[i][i] = 0 for child, d in graph[i]: dist[i][child] = d dist[child][i] = d for k in range(n): for i in range(n): for j in range(j): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) return dist #EDGES [w,x,y] def minimum_spanning_tree(edges, n): edges = sorted(edges) union_find = UnionFind(n) #implemented above used_edges = list() for w, x, y in edges: if union_find.find(x) != union_find.find(y): union_find.merge(x, y) used_edges.append([w,x,y]) return used_edges #FROM A GIVEN ROOT, RECOVER THE STRUCTURE def parents_children_root_unrooted_tree(tree, n, root = 0): q = deque() visited = [0] * n parent = [-1] * n children = [[] for i in range(n)] q.append(root) while q: all_done = 1 visited[q[0]] = 1 for child in tree[q[0]]: if not visited[child]: all_done = 0 q.appendleft(child) if all_done: for child in tree[q[0]]: if parent[child] == -1: parent[q[0]] = child children[child].append(q[0]) q.popleft() return parent, children # CALCULATING LONGEST PATH FOR ALL THE NODES def all_longest_path_passing_from_node(parent, children, n): q = deque() visited = [len(children[i]) for i in range(n)] downwards = [[0,0] for i in range(n)] upward = [1] * n longest_path = [1] * n for i in range(n): if not visited[i]: q.append(i) downwards[i] = [1,0] while q: node = q.popleft() if parent[node] != -1: visited[parent[node]] -= 1 if not visited[parent[node]]: q.append(parent[node]) else: root = node for child in children[node]: downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse = True)[0:2] s = [node] while s: node = s.pop() if parent[node] != -1: if downwards[parent[node]][0] == downwards[node][0] + 1: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1]) else: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0]) longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1 for child in children[node]: s.append(child) return longest_path def finding_ancestors(parent, queries, n): steps = int(ceil(log(n, 2))) ancestors = [[-1 for i in range(n)] for j in range(steps)] ancestors[0] = parent for i in range(1, steps): for node in range(n): if ancestors[i-1][node] != -1: ancestors[i][node] = ancestors[i-1][ancestors[i-1][node]] result = [] for node, k in queries: ans = node if k >= n: ans = -1 i = 0 while k > 0 and ans != -1: if k % 2: ans = ancestors[i][ans] k = k // 2 i += 1 result.append(ans) return result #Preprocessing in O(n log n). For each query O(log k) ### TBD SUCCESSOR GRAPH 7.5 ### TBD TREE QUERIES 10.2 da 2 a 4 ### TBD ADVANCED TREE 10.3 ### TBD GRAPHS AND MATRICES 11.3.3 e 11.4.3 e 11.5.3 (ON GAMES) ###################### ####### OTHERS ####### ###################### def prefix_sum(arr): r = [0] * (len(arr)+1) for i, el in enumerate(arr): r[i+1] = r[i] + el return r def nearest_from_the_left_smaller_elements(arr): n = len(arr) res = [-1] * n s = [] for i, el in enumerate(arr): while s and s[-1] >= el: s.pop() if s: res[i] = s[-1] s.append(el) return res def sliding_window_minimum(arr, k): res = [] q = deque() for i, el in enumerate(arr): while q and arr[q[-1]] >= el: q.pop() q.append(i) while q and q[0] <= i - k: q.popleft() if i >= k-1: res.append(arr[q[0]]) return res ### TBD COUNT ELEMENT SMALLER THAN SELF ###################### ## END OF LIBRARIES ## ###################### n, k = li() e = list() a = list() b = list() for i in range(n): [t,ai,bi] = li() if ai == 1 and bi == 1: e.append(t) elif ai == 1: a.append(t) elif bi == 1: b.append(t) presi = 0 tempo = 0 e = sorted(e) a = sorted(a) b = sorted(b) d = list() i = 0 while i < len(a) and i < len(b): d.append(a[i] + b[i]) i += 1 if len(d) + len(e) < k: print(-1) else: i = 0 j = 0 d.append(float('inf')) e.append(float('inf')) while i < len(e) and j < len(d) and presi < k: if e[i] > d[j]: tempo += d[j] j += 1 else: tempo += e[i] i += 1 presi += 1 print(tempo)
11
PYTHON3
from sys import stdin, exit input = stdin.readline def i(): return input() def ii(): return int(input()) def iis(): return map(int, input().split()) def liis(): return list(map(int, input().split())) def print_array(a): print(" ".join(map(str, a))) n, k = iis() alice = [] bob = [] both = [] for _ in range(n): t, a, b = iis() if a == 1 and b == 0: alice.append(t) elif a == 0 and b == 1: bob.append(t) elif a == 1 and b == 1: both.append(t) alice = sorted(alice)[::-1] bob = sorted(bob)[::-1] both = sorted(both)[::-1] time = 0 livros = 0 while k > 0 and (len(both) != 0 or (len(alice) != 0 and len(bob) != 0)): if len(both) and len(alice) and len(bob): separado = alice[-1]+bob[-1] junto = both[-1] if junto < separado: time += junto both.pop() else: time += separado alice.pop() bob.pop() elif len(both): time += both.pop() elif len(alice) and len(bob): time += alice.pop() time += bob.pop() else: continue k -= 1 if k == 0: print(time) else: print(-1)
11
PYTHON3
n,k=[int(x) for x in input().split()] a,b,ab=[0],[0],[0] for _ in range(n): p,q,r=[int(x) for x in input().split()] if q==1: if r==1: ab.append(p) else: a.append(p) else: if r==1: b.append(p) if len(ab)-1+min(len(a)-1,len(b)-1)<k: print(-1); exit() #print(a) #print(b) #print(ab) a.sort() b.sort() ab.sort() sumo=0 for i in range(len(a)): sumo+=a[i] a[i]=sumo sumo=0 for i in range(len(b)): sumo+=b[i] b[i]=sumo sumo=0 for i in range(len(ab)): sumo+=ab[i] ab[i]=sumo #print(a) #print(b) #print(ab) minans=int(1e10) for kp in range(max(0,k+1-min(len(a),len(b))),min(len(ab),k+1)): minans=min(minans,a[k-kp]+b[k-kp]+ab[kp]) print(minans)
11
PYTHON3
from sys import stdin input = stdin.readline if __name__ == '__main__': n, k = map(int, input().split()) al = [] bl = [] abl = [] for _ in range(n): t, a, b = map(int, input().split()) if a and b: abl.append(t) elif a: al.append(t) elif b: bl.append(t) al.sort() bl.sort() abl.sort() sl = list(map(lambda o: o[0] + o[1], zip(al, bl))) abl.reverse() sl.reverse() c = 0 while abl and sl and k: if abl[-1] < sl[-1]: c += abl.pop() else: c += sl.pop() k -= 1 if k: if len(abl) + len(sl) < k: print(-1) else: while k: if abl: c += abl.pop() else: c += sl.pop() k -= 1 print(c) else: print(c)
11
PYTHON3
import sys input = sys.stdin.readline from collections import * n, k = map(int, input().split()) d = defaultdict(list) for _ in range(n): t, a, b = map(int, input().split()) if a==1 and b==1: d[0].append(t) elif a==1 and b==0: d[1].append(t) elif a==0 and b==1: d[2].append(t) acc = defaultdict(list) for i in range(3): d[i].sort() acc[i].append(0) for ti in d[i]: acc[i].append(acc[i][-1]+ti) ans = 10**18 for i in range(min(k, len(d[0]))+1): if k-i>len(d[1]) or k-i>len(d[2]): continue ans = min(ans, acc[0][i]+acc[1][k-i]+acc[2][k-i]) if ans==10**18: print(-1) else: print(ans)
11
PYTHON3
n , k = map(int , input().split()) alice = list() bob = list() both = list() for i in range(n): t, a, b = map(int , input().split()) if a == 1: if b == 1: both.append(t) else: alice.append(t) else: if b == 1: bob.append(t) alice = sorted(alice) bob = sorted(bob) both = sorted(both) final = list() for i in range(min(len(alice) , len(bob))): final.append(alice[i] + bob[i]) fp = 0 bp = 0 time = 0 count = 0 while(count < k): if (fp+1) > len(final) and (bp+1) > len(both): break elif (fp+1) > len(final): time += both[bp] count += 1 bp += 1 elif (bp+1) > len(both): time += final[fp] count += 1 fp += 1 else: if final[fp] <= both[bp]: time += final[fp] count += 1 fp += 1 else: time += both[bp] count += 1 bp += 1 if count >= k: print(time) else: print(-1)
11
PYTHON3
n,k=map(int,input().split()) lst=[] for i in range(n): lst.append(list(map(int,input().split()))) alice=[] bob=[] same=[] for i in lst: if i[1]==1 and i[2]==0: alice.append(i[0]) elif i[2]==1 and i[1]==0: bob.append(i[0]) elif i[2]==1 and i[1]==1: same.append(i[0]) a=len(alice) b=len(bob) s=len(same) if a+s<k or b+s<k: print(-1) else: alice.sort() bob.sort() same.sort() l=0 n=0 ans=0 count=0 temp=min(a,b) while count<k and n<s and l<temp: if alice[l]+bob[l]<same[n] or n>=s: ans+=alice[l]+bob[l] l+=1 count+=1 #print('here') else: ans+=same[n] count+=1 n+=1 #print('here2') if count!=k and n==s: ans+=sum(alice[l:l+k-count])+sum(bob[l:l+k-count]) else: ans+=sum(same[n:n+k-count]) print(ans)
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):C.append(t);continue if(x==1):A.append(t);continue if(y==1):B.append(t) def fun(l): pre=[0] for i in l: pre.append(pre[-1]+i) return pre A.sort() B.sort() C.sort() a=fun(A) b=fun(B) c=fun(C) if(len(A)+len(C)<k or len(B)+len(C)<k):print(-1) else: ans=999999999999999999999999999 for i in range(min(len(C),k)+1): if(k-i<len(a) and k-i<len(b)):ans=min(ans,c[i]+a[k-i]+b[k-i]) print(ans)
11
PYTHON3
n , k = map(int , input().split()) books = [] alice = [] bobs = [] for _ in range(n): t , a , b = map(int , input().split()) if (a== 1 and b==1): books.append(t) elif (a == 1): alice.append(t) elif (b==1): bobs.append(t) books = sorted(books) alice = sorted(alice) bobs = sorted(bobs) b = 0 ab = 0 count = 0 ans = 0 while (count< k and (b < len(books) and (ab < len(alice) and ab < len(bobs)))): if (books[b] <= alice[ab]+bobs[ab]): ans += books[b] b+=1 else : ans += (alice[ab] + bobs[ab]) ab+=1 count+=1 if (count == k ): print(ans) else : while(count< k and (b < len(books) )): ans += books[b] b+=1 count+=1 while(count< k and(ab < len(alice) and ab < len(bobs))): ans += (alice[ab] + bobs[ab]) ab+=1 count+=1 if(count < k ): print(-1) else : print(ans)
11
PYTHON3
from collections import defaultdict as dd import sys input=sys.stdin.readline #n=int(input()) n,kk=map(int,input().split()) l=[] ans=0 for i in range(n): time,a,b=map(int,input().split()) l.append((time,a,b)) l.sort() la=[] lb=[] do=[] for i in l: time,a,b=i if(a and b): do.append(time) elif(a): la.append(time) elif(b): lb.append(time) i=0 j=0 k=0 ca=kk cb=kk while ca and cb: if(i<len(la)): if(j<len(lb)): if(k<len(do)): if(la[i]+lb[j]<=do[k]): ans+=la[i] ans+=lb[j] i+=1 j+=1 ca-=1 cb-=1 else: ans+=do[k] k+=1 ca-=1 cb-=1 else: ans+=la[i] ans+=lb[j] i+=1 j+=1 ca-=1 cb-=1 else: if(k<len(do)): ans+=do[k] k+=1 ca-=1 cb-=1 else: break else: if(k<len(do)): ans+=do[k] k+=1 ca-=1 cb-=1 else: break if(ca or cb): print(-1) else: print(ans)
11
PYTHON3
n,k = map(int,input().split()) inf = float("inf") a,b,c = [inf],[inf],[inf] a_cnt,b_cnt = 0,0 for i in range(n): u,v,w = map(int,input().split()) if v==1 and w==1: c.append(u) a_cnt += 1; b_cnt +=1 elif v==1: a.append(u) a_cnt += 1 elif w==1: b.append(u) b_cnt += 1 if a_cnt < k or b_cnt < k: print(-1) exit() a.sort(reverse=True) b.sort(reverse=True) c.sort(reverse=True) a_left,b_left,ans = k,k,0 while a_left > 0 or b_left > 0: if a_left and b_left and len(a)-1 and len(b)-1 and len(c)-1: if (a[-1] + b[-1]) >= c[-1] or len(a)-1 < a_left or len(b)-1 < b_left: ans += c.pop() else: ans += a.pop() + b.pop() a_left-=1;b_left-=1 else: best = inf if a_left and b_left: best = min(best,a[-1]+b[-1]) if a_left and not b_left: best = min(best,a[-1]) if b_left and not a_left: best = min(best,b[-1]) best = min(best,c[-1]) if best == c[-1]: ans += c.pop() a_left-=1;b_left-=1 elif best == a[-1]: ans += a.pop() a_left -=1 else: ans += b.pop() b_left-=1 print(ans)
11
PYTHON3
from sys import* input= stdin.readline for _ in range(1): n,k=map(int,input().split()) c=[] a=[] b=[] for _ in range(n): x,y,z=map(int,input().split()) if(y==1 and z==1): c.append(x) elif(y==1): a.append(x) elif(z==1): b.append(x) a.sort() b.sort() for i in range(min(len(a),len(b))): c.append(a[i]+b[i]) c.sort() if(len(c)>=k): print(sum(c[:k])) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<int> va; vector<int> vb; vector<int> vab; int n, k, a, b, t; cin >> n >> k; for (int p = 0; p < n; p++) { cin >> t >> a >> b; if (a == 1 && b == 1) vab.push_back(t); else if (a == 0 && b == 1) vb.push_back(t); else if (a == 1 && b == 0) va.push_back(t); } sort(va.begin(), va.end()); int na = va.size(); sort(vb.begin(), vb.end()); int nb = vb.size(); int nab = vab.size(); sort(vab.begin(), vab.end()); int ans = 0; int p = 0; int ai = 0; int bi = 0; int abi = 0; while (p < k) { if (ai < na && bi < nb && abi < nab) { if (va[ai] + vb[bi] <= vab[abi]) { ans = ans + va[ai] + vb[bi]; ai++; bi++; } else { ans = ans + vab[abi]; abi++; } p++; } else if (ai < na && bi < nb && abi >= nab) { ans = ans + va[ai] + vb[bi]; ai++; bi++; p++; } else if ((ai >= na || bi >= nb) && abi < nab) { ans = ans + vab[abi]; abi++; p++; } else break; } if (p == k) cout << ans; else cout << -1; }
11
CPP
n,k = list(map(int,input().split())) a11,a10,a01 = [],[],[] c,d = 0,0 for i in range(n): t,a,b = list(map(int,input().split())) if a==1 and b==1: a11.append(t) elif a==1 and b==0: a10.append(t) elif a==0 and b==1: a01.append(t) c+=a d+=b a11.sort() a10.sort() a01.sort() if c>=k and d>=k: ans,f = 0,0 p1,p2,p3 = 0,0,0 s1 = 10**10 s2 = 10**10 if len(a11)>=k: po = sum(a11[:k]) s1 = min(s1,po) if len(a10)>=k and len(a01)>=k: v1,v2 = sum(a10[:k]),sum(a01[:k]) s2 = min(s2,v1+v2) for i in range(k): if p2<len(a10) and p3<len(a01): if p1<len(a11): x = a10[p2] y = a01[p3] z = a11[p1] if z<x+y: p1+=1 else: p2+=1 p3+=1 ans+=min(x+y,z) else: x = a10[p2] y = a01[p3] ans+=x+y p2+=1 p3+=1 else: if p1<len(a11): ans+=a11[p1] p1+=1 else: f = 1 break if f==1: print(-1) else: print(min(ans,s1,s2)) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; template <typename T> void read(T &r) { static char c; r = 0; for (c = getchar(); c > '9' || c < '0'; c = getchar()) ; for (; c >= '0' && c <= '9'; r = (r << 1) + (r << 3) + (c ^ 48), c = getchar()) ; } const int maxn = 2e5 + 100; int n, m, k; struct node { int t, id; bool operator<(const node &b) const { return t == b.t ? id < b.id : t < b.t; } } A[4][maxn]; int num[4]; long long sums[4][maxn]; inline void init() { read(n), read(m), read(k); for (int i = 1; i <= n; ++i) { int t, a, b, p; read(t), read(a), read(b), p = a * 2 + b; A[p][++num[p]].id = i, A[p][num[p]].t = t; } for (int i = 0; i < 4; ++i) sort(A[i] + 1, A[i] + 1 + num[i]); for (int i = 0; i < 4; ++i) for (int j = 1; j <= num[i]; ++j) sums[i][j] = sums[i][j - 1] + A[i][j].t; } set<node> all, choose; int sum, need; inline void update() { if (need < 0) need = 0; set<node>::iterator it; bool flag; begin: flag = true; while (choose.size() > need) it = --choose.end(), sum -= it->t, all.insert(*it), choose.erase(it), flag = false; while (choose.size() < need && !all.empty()) sum += (it = all.begin())->t, choose.insert(*it), all.erase(it), flag = false; while (!choose.empty() && !all.empty() && (it = --choose.end())->t > all.begin()->t) { sum -= it->t, sum += all.begin()->t; all.insert(*it), choose.erase(it); choose.insert(*all.begin()), all.erase(all.begin()); flag = false; } if (!flag) goto begin; } int main() { init(); int start = 0; while (start <= num[3] && (k - start > num[1] || k - start > num[2] || m - start - (k - start) * 2 < 0)) ++start; if (start == num[3] + 1) { puts("-1"); return 0; } need = m - k * 2 + start; for (int i = 0; i < 3; ++i) for (int j = num[i]; j > (i == 0 ? 0 : k - start); --j) all.insert(A[i][j]); long long ans = 1ll << 60; int ansp = -1; update(); for (int i = start; i <= num[3]; ++i) { int res = sums[3][i] + sum; if (k - i >= 0) res += sums[1][k - i] + sums[2][k - i]; if (res < ans && ((k - i >= 0) ? (i + 2 * (k - i) + choose.size() == m) : (i + choose.size() == m))) ans = res, ansp = i; --need; if (k - i > 0) need += 2, all.insert(A[1][k - i]), all.insert(A[2][k - i]); update(); } printf("%lld\n", ans); all.clear(), choose.clear(); need = m - k * 2 + start; for (int i = 0; i < 3; ++i) for (int j = num[i]; j > (i == 0 ? 0 : k - start); --j) all.insert(A[i][j]); update(); for (int i = start; i <= num[3]; ++i) { if (i == ansp) { for (int j = 1; j <= i; ++j) printf("%d ", A[3][j].id); if (k - i > 0) for (int j = 1; j <= k - i; ++j) printf("%d %d ", A[1][j].id, A[2][j].id); for (set<node>::iterator it = choose.begin(); it != choose.end(); ++it) printf("%d ", it->id); return 0; } --need; if (k - i > 0) need += 2, all.insert(A[1][k - i]), all.insert(A[2][k - i]); update(); } puts("-1"); return 0; }
11
CPP
import sys import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n,k=map(int,input().split()) bothlike=[] alike=[] blike=[] for i in range(n): t,a,b=map(int,input().split()) if a==1 and b==1: bothlike.append(t) if a==1 and b==0: alike.append(t) if a==0 and b==1: blike.append(t) if len(alike)+len(bothlike)<k or len(blike)+len(bothlike)<k: print(-1) sys.exit() alike.sort() blike.sort() bothlike.sort() asum=[0] current=0 for i in range(len(alike)): current+=alike[i] asum.append(current) bsum=[0] current=0 for i in range(len(blike)): current+=blike[i] bsum.append(current) bothcurrent=0 ans=10**18 alen=len(alike) blen=len(blike) bothlen=len(bothlike) for i in range(bothlen+1): if i>0: bothcurrent+=bothlike[i-1] if i>k: break if k-i>alen or k-i>blen: continue ans=min(ans,asum[k-i]+bsum[k-i]+bothcurrent) print(ans)
11
PYTHON3
n, k = map(int, input().split()) both = [] alice = [] bob = [] for i in range(n): t, a, b = map(int, input().split()) if a and b: both.append(t) elif a: alice.append(t) elif b: bob.append(t) alice.sort(reverse=True) bob.sort(reverse=True) both.sort(reverse=True) def solve(): ak = k bk = k v = 0 while ak > 0 and bk > 0: if (not alice or not bob) and not both: return -1 if alice and bob and (not both or both[-1] > alice[-1] + bob[-1]): v += alice.pop() + bob.pop() else: v += both.pop() #print(alice, bob, both, ak,bk, v) ak -= 1 bk -= 1 while ak > 0: if not alice and not both: return -1 if alice and (not both or both[-1] > alice[-1]): v += alice.pop() else: v += both.pop() #print(alice, bob, both, ak, bk, v) ak -= 1 while bk > 0: if not bob and not both: return -1 if bob and (not both or both[-1] > bob[-1]): v += bob.pop() else: v += both.pop() bk -= 1 #print(alice, bob, ak, bk, v) return v print(solve())
11
PYTHON3
#include <bits/stdc++.h> using namespace std; const long long N = 1e9 + 5; bool col2(pair<long long, long long> p1, pair<long long, long long> p2) { if (p1.first == p2.first) return p2.second < p1.second; else return p1.first < p2.first; } struct comp { bool operator()(long long const &x, long long const &y) { return x > y; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(0); ; long long n, k; cin >> n >> k; vector<long long> a; vector<long long> b; vector<long long> both; for (long long i = 0; i < n; i++) { long long x, y, z; cin >> x >> y >> z; if (y == 1 && z == 1) both.push_back(x); else if (y == 1 && z != 1) a.push_back(x); else if (y != 1 && z == 1) b.push_back(x); } sort(a.begin(), a.end()); sort(b.begin(), b.end()); for (long long i = 0; i < min((long long)a.size(), (long long)b.size()); i++) both.push_back(a[i] + b[i]); sort(both.begin(), both.end()); long long ans1 = 0; for (long long i = 0; i < (long long)both.size(); i++) { if (k <= 0) break; ans1 += both[i]; k--; } if (k > 0) cout << -1 << endl; else cout << ans1 << endl; }
11
CPP
#include <bits/stdc++.h> using namespace std; int n, k, ans; multiset<int> alice, bob, both; int main() { cin >> n >> k; for (int i = 0; i < n; i++) { int t, a, b; cin >> t >> a >> b; if (a + b == 2) both.insert(t); else if (a) alice.insert(t); else if (b) bob.insert(t); } if (alice.size() + both.size() < k || bob.size() + both.size() < k) return cout << -1, 0; while (k && !both.empty() && !alice.empty() && !bob.empty()) { int fromAlice = *alice.begin(), fromBob = *bob.begin(), fromBoth = *both.begin(); if (fromBoth > fromAlice + fromBob) { alice.erase(alice.begin()); bob.erase(bob.begin()); ans += fromAlice + fromBob; } else { both.erase(both.begin()); ans += fromBoth; } k--; } while (k && !both.empty()) { ans += *both.begin(); both.erase(both.begin()); k--; } while (k && !alice.empty() && !bob.empty()) { ans += *alice.begin() + *bob.begin(); alice.erase(alice.begin()); bob.erase(bob.begin()); k--; } cout << ans; }
11
CPP
import sys, math input=sys.stdin.readline n,k=map(int,input().split()) both=[] a=[] b=[] for i in range(n): ti,ai,bi=map(int,input().split()) if ai==1 and bi==1: both.append(ti) elif ai==1 and bi==0: a.append(ti) elif ai==0 and bi==1: b.append(ti) both.sort() a.sort() b.sort() bothPointer = 0 aPointer = 0 bPointer = 0 alength = len(a) blength = len(b) bothlength = len(both) ans = [0]*(k+1) flag = True for i in range(1,k+1): if aPointer<alength and bPointer<blength: if bothPointer < bothlength: if a[aPointer] + b[bPointer] < both[bothPointer]: ans[i] = ans[i-1] + a[aPointer] + b[bPointer] aPointer+=1 bPointer+=1 else: ans[i]=ans[i-1]+both[bothPointer] bothPointer+=1 else: ans[i] = ans[i-1] + a[aPointer] + b[bPointer] aPointer+=1 bPointer+=1 else: if bothPointer < bothlength: ans[i]=ans[i-1]+both[bothPointer] bothPointer+=1 else: flag = False break if flag: print(ans[k]) else: print(-1)
11
PYTHON3
n , k = input().split() n = int(n) k = int(k) c = [] a = [] b = [] for i in range(n): t,al,bo = input().split() if(al == '1' and bo == '1'): c.append(int(t)) elif(al == '1'): a.append(int(t)) elif(bo == '1'): b.append(int(t)) if(len(c)+len(a) < k or len(c)+len(b) < k): print(-1) quit() c.sort() a.sort() b.sort() for i in range(1,len(c)): c[i] = c[i] + c[i-1] for i in range(1,len(a)): a[i] = a[i] + a[i-1] for i in range(1,len(b)): b[i] = b[i] + b[i-1] #high = 2147483640 high = 2000000000 p = 0 tempo = 0 while(p <= len(c) and p<= k): if(p>0): tempo = c[p-1] else: tempo = 0 dif = k-p if(len(a)>= dif and len(b)>=dif): if(dif > 0): tempo = tempo + (a[dif-1]+ b[dif-1]) if(high >= tempo): high = tempo p = p + 1 print(high)
11
PYTHON3
n,k=map(int,input().split());abt=[];at=[];bt=[] for i in range(n): t,a,b=map(int,input().split()) if a&b:abt.append(t) elif a:at.append(t) elif b:bt.append(t) at.sort();bt.sort() for i in range(min(len(at),len(bt))):abt.append((at[i]+bt[i])) if len(abt)<k:print(-1) else:print(sum(sorted(abt)[:k]))
11
PYTHON3
#include <bits/stdc++.h> using namespace std; using pi = pair<long long, long long>; const long long inf = (long long)2e9 + 5; signed main() { ios::sync_with_stdio(false); cin.tie(0); long long n, m, k; cin >> n >> m >> k; vector<pi> w[2][2]; for (long long i = 0; i < n; i++) { long long t, a, b; cin >> t >> a >> b; w[a][b].emplace_back(t, i); } if (((long long)(w[1][1]).size()) + min(((long long)(w[0][1]).size()), ((long long)(w[1][0]).size())) < k) { cout << -1 << '\n'; return 0; } long long res = inf, id[2][2]; long long cur[2][2], pt[2][2], z[2][2]; for (long long a : {0, 1}) { for (long long b : {0, 1}) { id[a][b] = -1; cur[a][b] = pt[a][b] = 0; while (((long long)(w[a][b]).size()) < m + 5) { w[a][b].emplace_back(inf, -1); } z[a][b] = ((long long)(w[a][b]).size()); sort((w[a][b]).begin(), (w[a][b]).end()); } } long long want[2][2]; for (long long i = k; i >= 0; i--) { want[0][0] = 0; want[0][1] = want[1][0] = k - i; want[1][1] = i; for (long long a : {0, 1}) { for (long long b : {0, 1}) { while (pt[a][b] < want[a][b]) { cur[a][b] += w[a][b][pt[a][b]++].first; } } } while (pt[1][1] + pt[1][0] + pt[0][1] + pt[0][0] < m) { cur[1][1] += w[1][1][pt[1][1]++].first; } while (pt[0][0] + pt[0][1] + pt[1][0] + pt[1][1] > m) { bool found = false; for (long long a : {0, 1}) { for (long long b : {0, 1}) { if (pt[a][b] > want[a][b]) { cur[a][b] -= w[a][b][--pt[a][b]].first; found = true; break; } } if (found) { break; } } if (!found) { break; } } while (true) { pair<long long, pi> add = {inf, {-1, -1}}, rem = {-inf, {-1, -1}}; for (long long a : {0, 1}) { for (long long b : {0, 1}) { add = min(add, make_pair(w[a][b][pt[a][b]].first, make_pair(a, b))); if (pt[a][b] > want[a][b]) { rem = max(rem, make_pair(w[a][b][pt[a][b] - 1].first, make_pair(a, b))); } } } if (add.first < rem.first) { long long a = add.second.first, b = add.second.second; cur[a][b] += w[a][b][pt[a][b]++].first; a = rem.second.first, b = rem.second.second; cur[a][b] -= w[a][b][--pt[a][b]].first; } else { break; } } if (pt[1][1] + min(pt[0][1], pt[1][0]) >= k && pt[1][1] + pt[1][0] + pt[0][1] + pt[0][0] == m) { long long val = cur[0][0] + cur[1][0] + cur[0][1] + cur[1][1]; if (val < res) { res = val; for (long long a : {0, 1}) { for (long long b : {0, 1}) { id[a][b] = pt[a][b]; } } } } --pt[1][1]; if (pt[1][1] >= 0) { cur[1][1] -= w[1][1][pt[1][1]].first; } } if (res == inf) { cout << -1 << '\n'; return 0; } cout << res << '\n'; for (long long a : {0, 1}) { for (long long b : {0, 1}) { for (long long i = 0; i < id[a][b]; i++) { cout << w[a][b][i].second + 1 << ' '; } } } cout << endl; return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; const int N = 200005; long long t, n, m, k, q, a, b, x, y, ans, arr[N]; long long mod = 998244353; string s; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); ; t = 1; while (t--) { cin >> n >> k; ans = 0, x = 0, y = 0; priority_queue<int, vector<int>, greater<int>> alice, bob, both; for (int i = 0; i < n; ++i) { cin >> m >> a >> b; x += a; y += b; if (a && b) both.push(m); else if (a) alice.push(m); else if (b) bob.push(m); } if (x < k || y < k) { cout << -1 << endl; continue; } while (k--) { if (!both.empty() && !alice.empty() && !bob.empty()) { if (both.top() <= alice.top() + bob.top()) ans += both.top(), both.pop(); else ans += alice.top() + bob.top(), alice.pop(), bob.pop(); } else if (both.empty()) ans += alice.top() + bob.top(), alice.pop(), bob.pop(); else ans += both.top(), both.pop(); } cout << ans << endl; } return 0; }
11
CPP
from sys import stdin,stdout input = stdin.readline #print = stdout.write n,k = map(int,input().split()) com = [] a = [] b = [] for _ in range(n): t,ai,bi = map(int,input().split()) if ai==1==bi: com+=[t] elif ai==1: a+=[t] elif bi==1: b+=[t] a.sort(reverse=True) b.sort(reverse=True) com.sort(reverse=True) ak,bk = 0,0 ans = 0 while ak!=k and bk!=k: if a and b and com: if a[-1]+b[-1]<=com[-1]: ans+=a[-1]+b[-1] a.pop() b.pop() else: ans+=com[-1] com.pop() ak+=1 bk+=1 elif a and b: ans+=a[-1]+b[-1] a.pop() b.pop() ak+=1 bk+=1 elif com: ans+=com[-1] com.pop() ak+=1 bk+=1 else: print(-1) break else: print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; vector<long long int> v, a1, b1; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long int n, k; cin >> n >> k; pair<long long int, pair<long long int, long long int> > p[n]; for (long long int i = 0; i < n; i++) { long long int t, a, b; cin >> t >> a >> b; p[i] = {t, {a, b}}; } sort(p, p + n); long long int ans = 0; for (long long int i = 0; i < n; i++) { if (p[i].second.first == 1 && p[i].second.second == 1) { ans += p[i].first; v.push_back(p[i].first); k--; } if (k == 0) break; } long long int flaga = 0; long long int temp = 0; for (long long int i = 0; i < n; i++) { if (flaga == k) temp = 1; if (p[i].second.first == 1 && p[i].second.second == 0) { if (temp == 1) a1.push_back(p[i].first); else { ans += p[i].first; flaga++; } } } long long int flagb = 0; temp = 0; for (long long int i = 0; i < n; i++) { if (flagb == k) temp = 1; if (p[i].second.first == 0 && p[i].second.second == 1) { if (temp == 1) b1.push_back(p[i].first); else { ans += p[i].first; flagb++; } } } long long int q = v.size() - 1; if (v.size() == 0) q = -1; for (long long int i = 0; i < a1.size() && i < b1.size() && q >= 0; i++) { if (a1[i] + b1[i] < v[q]) { ans += (a1[i] + b1[i] - v[q--]); } else break; } if (flaga == k && flagb == k) cout << ans << "\n"; else cout << -1 << "\n"; return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; void solve() { long long n, k; cin >> n >> k; vector<long long> v1, v2; vector<long long> v; for (long long i = 0; i < n; i++) { long long t1, a, b; cin >> t1 >> a >> b; if (a == 1) { if (b == 1) v.push_back(t1); else v1.push_back(t1); } else if (b == 1) { v2.push_back(t1); } } if ((v1.size() + v.size() < k) || (v2.size() + v.size() < k)) { cout << "-1"; return; } sort(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); sort(v.begin(), v.end()); long long t = 0, cnt = 0, i = 0, j = 0; while (cnt < k) { if (i < v1.size() && i < v2.size()) { if (j < v.size()) { if (v1[i] + v2[i] >= v[j]) { t += v[j]; cnt++; j++; } else { t += v1[i]; t += v2[i]; cnt++; i++; } } else { long long c = cnt, p = i; while (c < k) { t += v1[i]; i++; c++; } while (cnt < k) { t += v2[p]; p++; cnt++; } } } else { while (cnt < k) { t += v[j]; cnt++; j++; } } } cout << t; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long t = 1; while (t--) { solve(); } }
11
CPP
[N,K] = list(map(int, input().split())) L = [[[] for i in range(2)]for j in range(2)] for i in range(N): [t, a, b] = list(map(int, input().split())) L[a][b].append(t) INF = int(1e12) for i in range(2): for j in range(2): L[i][j].sort() for k in range(K - len(L[i][j])): L[i][j].append(INF) ans = INF now = 0 for i in range(K): now += L[1][1][i] ans = min(ans, now) for i in range(K): now -= L[1][1][K-i-1] now += L[1][0][i] now += L[0][1][i] ans = min (ans, now) if ans >= INF: ans = -1 print(ans)
11
PYTHON3
from sys import stdin,stdout from math import gcd,sqrt from collections import deque input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') L=lambda:list(R()) P=lambda x:stdout.write(x) hg=lambda x,y:((y+x-1)//x)*x pw=lambda x:1 if x==1 else 1+pw(x//2) chk=lambda x:chk(x//2) if not x%2 else True if x==1 else False N=10**10+7 n,k=R() A=[] B=[] D=[] for i in range(n): t,a,b=R() if a==b==1:D+=t, elif a:A+=t, elif b:B+=t, A.sort() B.sort() for i in range(min(len(A),len(B))): D+=A[i]+B[i], D.sort() if len(D)>=k:print(sum(D[:k])) else:print(-1)
11
PYTHON3
from collections import deque n,k=map(int,input().split()) s,s1,s2=deque(),deque(),deque() for i in range(n): a,b,c=map(int,input().split()) if(b==1)and(c==1): s.append(a) elif(b==1)and(c==0): s1.append(a) elif(b==0)and(c==1): s2.append(a) x,y=0,0 sum=0 s1=deque(sorted(s1)) s2=deque(sorted(s2)) s=deque(sorted(s)) while(len(s)!=0)and(len(s1)!=0)and(len(s2)!=0): if(x==k)or(y==k): break if(s[0]<=s1[0]+s2[0]): sum=sum+s.popleft() else: sum=sum+s1.popleft() sum=sum+s2.popleft() x+=1 y+=1 if(x!=k)and(y!=k)and(len(s1)==0): while(x!=k)and(y!=k)and(len(s)!=0): sum=sum+s.popleft() x+=1 y+=1 if(x!=k)and(y!=k)and(len(s2)==0): while(x!=k)and(y!=k)and(len(s)!=0): sum=sum+s.popleft() y+=1 x+=1 if(x!=k): while(len(s1)!=0)and(x!=k): sum=sum+s1.popleft() x+=1 if(y!=k): while(len(s2)!=0)and(y!=k): sum=sum+s2.popleft() y+=1 if(x==k)and(y==k): print(sum) else: print(-1)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; bool comp(pair<int, pair<int, int> > a, pair<int, pair<int, int> > b) { return a.first < b.first; } int main() { int n, k; cin >> n >> k; vector<pair<int, pair<int, int> > > book; for (int i = 0; i < n; i++) { pair<int, pair<int, int> > temp; cin >> temp.first >> temp.second.first >> temp.second.second; book.push_back(temp); } stack<int> alice, bob, both; sort(book.begin(), book.end(), comp); for (int i = 0; i < n; i++) { int t = book[i].first; bool a = book[i].second.first; bool b = book[i].second.second; if (a && b) { int t1 = 0, t2 = 0; if (!alice.empty()) { t1 = alice.top(); } if (!bob.empty()) { t2 = bob.top(); } if (t1 + t2 >= t) { both.push(t); if (alice.size() + both.size() > k) { alice.pop(); } if (bob.size() + both.size() > k) { bob.pop(); } } else { if (alice.size() + bob.size() + 2 * both.size() < 2 * k) { both.push(t); } if (alice.size() + both.size() > k) { alice.pop(); } if (bob.size() + both.size() > k) { bob.pop(); } } } else if (a) { if (alice.size() + both.size() < k) { alice.push(t); } } else if (b) { if (bob.size() + both.size() < k) { bob.push(t); } } } if (alice.size() + bob.size() + 2 * both.size() < 2 * k) { cout << -1 << endl; } else { int ans = 0; while (!alice.empty()) { ans += alice.top(); alice.pop(); } while (!bob.empty()) { ans += bob.top(); bob.pop(); } while (!both.empty()) { ans += both.top(); both.pop(); } cout << ans << endl; } }
11
CPP
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools # import time,random,resource # sys.setrecursionlimit(10**6) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 mod2 = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def pe(s): return print(str(s), file=sys.stderr) def JA(a, sep): return sep.join(map(str, a)) def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a) def IF(c, t, f): return t if c else f def YES(c): return IF(c, "YES", "NO") def Yes(c): return IF(c, "Yes", "No") def main(): t = 1 rr = [] for _ in range(t): n,k = LI() tab = [LI() for _ in range(n)] a0 = [] a1 = [] a2 = [] for t,a,b in tab: if a and b: a0.append(t) elif a: a1.append(t) elif b: a2.append(t) if len(a0) + min(len(a1), len(a2)) < k: return -1 a0.sort() a1.sort() a2.sort() a0.append(inf) a1.append(inf) a2.append(inf) i0 = 0 ii = 0 r = 0 for _ in range(k): if a0[i0] < a1[ii] + a2[ii]: r += a0[i0] i0 += 1 else: r += a1[ii] + a2[ii] ii += 1 rr.append(r) return JA(rr, "\n") print(main())
11
PYTHON3
from sys import stdin,stdout input = stdin.readline from collections import deque as dq mp = lambda : map(int,input().split()) it = lambda: int(input()) a,b = mp() comman =[] alice =[] bob =[] for books in range(a): t,x,y = mp() if x==y==1: comman.append(t) elif x&1: alice.append(t) elif y&1 : bob.append(t) comman = dq(sorted(comman)) alice = dq(sorted(alice)) bob = dq(sorted(bob)) time =0 while b : if len(alice) and len(bob) and len(comman): if alice[0] + bob[0] <=comman[0]: time+=(alice[0]+bob[0]) alice.popleft() bob.popleft() else: time+=comman[0] comman.popleft() else: if len(comman)==0: if len(alice)>=b and len(bob)>=b: for ele in range(b): time+=(alice[ele] + bob[ele]) else: time =-1 else: if len(comman)>=b: for ele in range(b): time+=comman[ele] else: time =-1 break b-=1 print(time)
11
PYTHON3
R=lambda:map(int,input().split()) s=sorted n,k=R() _,u,v,w=l=[[],[],[],[]] for _ in[0]*n:t,a,b=R();l[2*a+b]+=t, a=*map(sum,zip(s(u),s(v))),*w print(sum((s(a)+[-sum(a)-1])[:k]))
11
PYTHON3
n, k = map(int, input().split()) alice = [] bob = [] both = [] for _ in range(n): t, a, b = map(int, input().split()) if a == 1 and b == 1: both.append((t, a, b)) elif a == 1 and b == 0: alice.append((t, a, b)) elif a == 0 and b == 1: bob.append((t, a, b)) alice.sort() bob.sort() both.sort() ans = 0 ca = 0 cb = 0 ia = 0 ib = 0 iboth = 0 #print(alice, bob, both) while ca < k and cb < k and (ia < len(alice) and ib < len(bob) or iboth < len(both)): if iboth >= len(both) or ia < len(alice) and ib < len(bob) and alice[ia][0] + bob[ib][0] < both[iboth][0]: ans += alice[ia][0] + bob[ib][0] ia += 1 ib += 1 else: ans += both[iboth][0] iboth += 1 ca += 1 cb += 1 if cb >= k and ca >= k: print(ans) else: print(-1)
11
PYTHON3
import sys n, k = map(int, input().split()) a = [] b = [] g = [] for i in range(n): t, x, y = map(int, input().split()) if x and y: a.append(t) elif x: g.append(t) elif y: b.append(t) a.sort() b.sort() g.sort() t = 0 i = 0 j = 0 for o in range(k): if i < len(a) and j < min(len(b), len(g)): if a[i] < g[j] + b[j]: t += a[i] i += 1 else: t += g[j] + b[j] j += 1 elif i < len(a): t += a[i] i += 1 elif j < min(len(b), len(g)): t += g[j] + b[j] j += 1 else: print(-1) sys.exit(0) print(t)
11
PYTHON3
# from functools import lru_cache from sys import stdin, stdout import sys from math import * # from collections import deque # sys.setrecursionlimit(3*int(1e5)) # input = stdin.buffer.readline # print = stdout.write # @lru_cache() n,k=map(int,input().split()) a=[] bt=[] b=[] for i in range(n): x,y,z=map(int,input().split()) if(y==z==1): bt.append(x) elif(y==1): a.append(x) elif(z==1): b.append(x) a.sort() bt.sort() b.sort() ans=inf for i in range(1,len(a)): a[i]=a[i]+a[i-1] for i in range(1,len(b)): b[i]=b[i]+b[i-1] for i in range(1,len(bt)): bt[i]+=bt[i-1] y=min(len(bt),k) while(y>=0): x=min(len(a),len(b),k-y-1) # print(y,x) if(x==-1): ans=min(ans,bt[y-1]) elif(y==0 and x<len(a) and x<len(b)): ans=min(ans,a[x]+b[x]) elif(y+x+1==k and x<len(a) and x<len(b)): ans=min(ans,bt[y-1]+a[x]+b[x]) y-=1 # elif(x+y) if(ans==inf): print(-1) else: print(ans)
11
PYTHON3
#include <bits/stdc++.h> using namespace std; long long n, m, d, nn = 0, ttl = 0, fq[4], sm = 0, dd, sq[200069], zs = 0, inf = 1e18; pair<long long, long long> a[4][200069]; multiset<pair<long long, long long>> ms[2]; multiset<pair<long long, long long>>::iterator it; void blc() { for (; nn < dd && !ms[1].empty(); nn++) { it = ms[1].begin(); ms[0].insert(*it); sm += (*it).first; ms[1].erase(it); } for (; nn > dd && !ms[0].empty(); nn--) { it = ms[0].end(); it--; ms[1].insert(*it); sm -= (*it).first; ms[0].erase(it); } } void ins(pair<long long, long long> x) { ms[0].insert(x); nn++; sm += x.first; blc(); } void ers(pair<long long, long long> x) { it = ms[0].find(x); if (it != ms[0].end()) { ms[0].erase(it); nn--; sm -= x.first; } else { ms[1].erase(ms[1].find(x)); } blc(); } int main() { long long i, j, ii, k, w, mk, mn, e; pair<long long, long long> z = {inf, -1}; scanf("%lld%lld%lld", &n, &m, &d); for (i = 1; i <= n; i++) { scanf("%lld%lld", &w, &k); mk = k * 2; scanf("%lld", &k); mk |= k; fq[mk]++; a[mk][fq[mk]] = {w, i}; } mn = min(min(fq[1], fq[2]), d); if (fq[3] + mn < d) { printf("-1\n"); return 0; } for (i = 0; i < 4; i++) { sort(a[i] + 1, a[i] + fq[i] + 1); } dd = m - d - mn; for (i = 0; i < 4; i++) { k = (i < 3 ? mn : d - mn) * !!i; for (j = 1; j <= fq[i]; j++) { if (j <= k) { ttl += a[i][j].first; } else { ins(a[i][j]); } } } for (i = d - mn; i <= min(d, fq[3]); i++) { if (dd >= 0) { z = min(z, {ttl + sm, i}); } if (i < min(d, fq[3])) { dd++; blc(); for (ii = 1; ii <= 2; ii++) { ttl -= a[ii][d - i].first; ins(a[ii][d - i]); } ttl += a[3][i + 1].first; ers(a[3][i + 1]); } } if (z.first == inf) { printf("-1\n"); return 0; } e = z.second; ttl = 0; for (ii = 0; ii < 2; ii++) { ms[ii].clear(); } nn = 0; sm = 0; dd = m - (d * 2 - e); for (i = 0; i < 4; i++) { k = (i < 3 ? d - e : e) * !!i; for (j = 1; j <= fq[i]; j++) { if (j <= k) { zs++; sq[zs] = a[i][j].second; } else { ins(a[i][j]); } } } for (; !ms[0].empty(); ms[0].erase(it)) { it = ms[0].begin(); zs++; sq[zs] = (*it).second; } printf("%lld\n", z.first); for (i = 1; i <= zs; i++) { printf("%lld%c", sq[i], " \n"[i == zs]); } }
11
CPP
from sys import * n, k = [int(x) for x in stdin.readline().split()] lk1 = [] lk2 = [] lk3 = [] for _ in range (n): time, x, y = [int(x) for x in stdin.readline().split()] if x == 1 and y == 1: lk3.append(time) elif x == 1: lk1.append(time) elif y == 1: lk2.append(time) lk1.sort() lk2.sort() cnt = min(len(lk1), len(lk2)) for i in range(cnt): lk3.append(lk1[i] + lk2[i]) lk3.sort() if len(lk3) < k: stdout.write(str(-1) + '\n') else: sum = 0 for i in range (k): sum += lk3[i] stdout.write(str(sum) + '\n')
11
PYTHON3
from heapq import * from collections import * import os import sys from io import BytesIO, IOBase import math ins = lambda: [int(x) for x in input()] inp = lambda: int(input()) inps = lambda: [int(x) for x in input().split()] def main(): #dd n,k=inps() bks=[[0] for i in range(4)] for i in range(n): t,a,b=inps() bks[2*a+b].append(t) for i in range(4): bks[i].sort() for i in range(4): for j in range(len(bks[i])-1): bks[i][j+1]+=bks[i][j] ans=float('inf') for i in range(k+1): if len(bks[3])>i and len(bks[1])>k-i and len(bks[2])>k-i: ans=min(ans,bks[3][i]+bks[1][k-i]+bks[2][k-i]) if ans!=float('inf'): print(ans) else: print(-1) 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") # endregion if __name__ == "__main__": main()
11
PYTHON3
#!/usr/bin/env python3 import sys import heapq input=sys.stdin.readline n,k=map(int,input().split()) arr=[list(map(int,input().split())) for _ in range(n)] cnt1=0 cnt2=0 for t,a,b in arr: if a==1: cnt1+=1 if b==1: cnt2+=1 if cnt1<k or cnt2<k: print(-1) exit() arr=sorted(arr,key=lambda x:x[0]) arr=sorted(arr,reverse=True,key=lambda x:x[1]) ans=0 cnt=0 for i in range(k): ans+=arr[i][0] if arr[i][2]==1: cnt+=1 if cnt==k: print(ans) exit() q1=[] q2=[] q3=[] for t,a,b in arr[:k]: if a==1 and b==0: heapq.heappush(q1,-t) for t,a,b in arr[k:]: if a==1 and b==1: heapq.heappush(q2,t) if a==0 and b==1: heapq.heappush(q3,t) INF=10**18 while cnt<k: diff1=INF if len(q2)!=0: cost1=heapq.heappop(q1) heapq.heappush(q1,cost1) cost2=heapq.heappop(q2) heapq.heappush(q2,cost2) diff1=cost1+cost2 diff2=INF if len(q3)!=0: cost3=heapq.heappop(q3) heapq.heappush(q3,cost3) diff2=cost3 if diff1!=INF and diff2==INF: ans+=diff1 heapq.heappop(q1) heapq.heappop(q2) elif diff1==INF and diff2!=INF: ans+=diff2 heapq.heappop(q3) else: if diff1<=diff2: ans+=diff1 heapq.heappop(q1) heapq.heappop(q2) else: ans+=diff2 heapq.heappop(q3) cnt+=1 print(ans)
11
PYTHON3
n,k = map(int, input().split()) alice = [] bob = [] common = [] for i in range(n): t, a, b = map(int, input().split()) if a and b: common.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))): common.append(alice[i]+bob[i]) if len(common)<k: print(-1) else: common.sort() print(sum(common[:k]))
11
PYTHON3
n,k=map(int,input().split()) z=[] x=[] y=[] for i in range(n): t,a,b=map(int,input().split()) if a&b: z.append(t) elif a: x.append(t) elif b: y.append(t) x.sort() y.sort() for i in range(min(len(x),len(y))): z.append(x[i]+y[i]) if len(z)<k: print(-1) else: print(sum(sorted(z)[:k]))
11
PYTHON3
#include <bits/stdc++.h> const int INF = 2e9 + 1; int main() { std::ios::sync_with_stdio(false); std::cin.tie(NULL); int n, k; std::cin >> n >> k; std::vector<int> t(n), a(n), b(n); std::vector<int> v[2][2]; for (int i = 0; i < n; i++) { std::cin >> t[i] >> a[i] >> b[i]; v[a[i]][b[i]].push_back(t[i]); } long long answer = INF; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int K = 0; K < k; ++K) { v[i][j].push_back(INF); } std::sort(v[i][j].begin(), v[i][j].end()); } } long long now = 0; for (int i = 0; i < k; i++) { now += v[1][1][i]; } answer = std::min(answer, now); for (int i = 0; i < k; i++) { now -= v[1][1][k - i - 1]; now += v[1][0][i]; now += v[0][1][i]; answer = std::min(answer, now); } if (answer < INF) std::cout << answer << '\n'; else std::cout << -1 << '\n'; return 0; }
11
CPP
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f, MAXN = 2e6 + 50; const long long LINF = 2e9 + 1000, MOD = 998244353; const double Pi = acos(-1), EPS = 1e-6; void test() { cerr << "\n"; } template <typename T, typename... Args> void test(T x, Args... args) { cerr << x << " "; test(args...); } inline long long qpow(long long a, long long b) { return b ? ((b & 1) ? a * qpow(a * a % MOD, b >> 1) % MOD : qpow(a * a % MOD, b >> 1)) % MOD : 1; } inline long long qpow(long long a, long long b, long long c) { return b ? ((b & 1) ? a * qpow(a * a % c, b >> 1) % c : qpow(a * a % c, b >> 1)) % c : 1; } inline long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } inline long long cede(long long a, long long b) { if (b < 0) return cede(-a, -b); if (a < 0) return a / b; return (a + b - 1) / b; } inline long long flde(long long a, long long b) { if (b < 0) return flde(-a, -b); if (a < 0) return (a - b + 1) / b; return a / b; } inline int sign(double x) { return x < -EPS ? -1 : x > EPS; } inline int dbcmp(double l, double r) { return sign(l - r); } namespace Fast_IO { const int MAXL((1 << 18) + 1); int iof, iotp; char ioif[MAXL], *ioiS, *ioiT, ioof[MAXL], *iooS = ioof, *iooT = ioof + MAXL - 1, ioc, iost[55]; char Getchar() { if (ioiS == ioiT) { ioiS = ioif; ioiT = ioiS + fread(ioif, 1, MAXL, stdin); return (ioiS == ioiT ? EOF : *ioiS++); } else return (*ioiS++); } void Write() { fwrite(ioof, 1, iooS - ioof, stdout); iooS = ioof; } void Putchar(char x) { *iooS++ = x; if (iooS == iooT) Write(); } inline int read() { int x = 0; for (iof = 1, ioc = Getchar(); ioc < '0' || ioc > '9';) iof = ioc == '-' ? -1 : 1, ioc = Getchar(); for (x = 0; ioc <= '9' && ioc >= '0'; ioc = Getchar()) x = (x << 3) + (x << 1) + (ioc ^ 48); return x * iof; } inline long long read_ll() { long long x = 0; for (iof = 1, ioc = Getchar(); ioc < '0' || ioc > '9';) iof = ioc == '-' ? -1 : 1, ioc = Getchar(); for (x = 0; ioc <= '9' && ioc >= '0'; ioc = Getchar()) x = (x << 3) + (x << 1) + (ioc ^ 48); return x * iof; } template <class Int> void Print(Int x, char ch = '\0') { if (!x) Putchar('0'); if (x < 0) Putchar('-'), x = -x; while (x) iost[++iotp] = x % 10 + '0', x /= 10; while (iotp) Putchar(iost[iotp--]); if (ch) Putchar(ch); } void Getstr(char *s, int &l) { for (ioc = Getchar(); ioc < 'a' || ioc > 'z';) ioc = Getchar(); for (l = 0; ioc <= 'z' && ioc >= 'a'; ioc = Getchar()) s[l++] = ioc; s[l] = 0; } void Putstr(const char *s) { for (int i = 0, n = strlen(s); i < n; ++i) Putchar(s[i]); } } // namespace Fast_IO using namespace Fast_IO; vector<pair<int, int> > a, b, c; int prea[MAXN], preb[MAXN], prec[MAXN]; int cnt[MAXN], sum[MAXN]; int lowbit(int x) { return x & -x; } const int MAXT = 1e4 + 50; void add(int *tree, int x, int val) { while (x <= MAXT) { tree[x] += val; x += lowbit(x); } } int ask(int *tree, int x) { int ans = 0; while (x) { ans += tree[x]; x -= lowbit(x); } return ans; } void UPD(int i, int k) { if (i > 0 && i < a.size()) add(cnt, a[i].first, -1), add(sum, a[i].first, -a[i].first); i--; if (k - i > 0 && k - i < b.size()) add(cnt, b[k - i].first, 1), add(sum, b[k - i].first, b[k - i].first); if (k - i > 0 && k - i < c.size()) add(cnt, c[k - i].first, 1), add(sum, c[k - i].first, c[k - i].first); } void work() { int n, k, m; scanf("%d%d%d", &n, &m, &k); a.push_back({0, 0}); b.push_back({0, 0}); c.push_back({0, 0}); int cnta = 0, cntb = 0; set<pair<int, int> > st; for (int i = 1; i <= n; i++) { int t, x, y; scanf("%d%d%d", &t, &x, &y); st.insert({t, i}); cnta += x; cntb += y; if (x && y) { a.push_back({t, i}); add(cnt, t, 1); add(sum, t, t); } else if (x && !y) b.push_back({t, i}); else if (y && !x) c.push_back({t, i}); else { add(cnt, t, 1); add(sum, t, t); } } sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(c.begin(), c.end()); for (int i = k + 2; i < b.size(); i++) add(cnt, b[i].first, 1), add(sum, b[i].first, b[i].first); for (int i = k + 2; i < c.size(); i++) add(cnt, c[i].first, 1), add(sum, c[i].first, c[i].first); if (cnta < k || cntb < k) { printf("-1"); return; } for (int i = 1; i < a.size(); i++) prea[i] = prea[i - 1] + a[i].first; for (int i = 1; i < b.size(); i++) preb[i] = preb[i - 1] + b[i].first; for (int i = 1; i < c.size(); i++) prec[i] = prec[i - 1] + c[i].first; int ans = LINF; int maxi = 0, maxl = 0; for (int i = 0; i < a.size(); i++) { UPD(i, k); if (k - i >= b.size() || k - i >= c.size() || i + k - i + k - i > m) { continue; } if (k - i < 0) break; int lef = m - (i + k - i + k - i); if (lef < 0) { continue; } int l = 0, r = MAXT; while (l < r) { int mid = l + r >> 1; if (ask(cnt, mid) >= lef) r = mid; else l = mid + 1; } if (r == MAXT) { continue; } int tmp; if (l == 0) tmp = 0; else tmp = ask(sum, l - 1) + l * (lef - ask(cnt, l - 1)); if (ans > prea[i] + preb[k - i] + prec[k - i] + tmp) { ans = prea[i] + preb[k - i] + prec[k - i] + tmp; maxi = i; maxl = l; } } if (ans == LINF) { printf("-1\n"); return; } printf("%d\n", ans); for (int i = 1; i <= maxi; i++) printf("%d ", a[i].second), st.erase({a[i].first, a[i].second}); for (int i = 1; i <= k - maxi; i++) printf("%d %d ", b[i].second, c[i].second), st.erase({b[i].first, b[i].second}), st.erase({c[i].first, c[i].second}); for (int i = 1; i <= m - (maxi + k - maxi + k - maxi); i++) printf("%d ", (*st.begin()).second), st.erase(st.begin()); } int main() { work(); }
11
CPP