solution
stringlengths 11
983k
| difficulty
int64 0
21
| language
stringclasses 2
values |
---|---|---|
from sys import stdin, setrecursionlimit, stdout
#setrecursionlimit(1000000)
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heappushpop, heapreplace
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline().rstrip()
def lsi(): return list(si())
#mod=1000000007
res=['YES', 'NO']
############# CODE STARTS HERE #############
test_case=1
while test_case:
test_case-=1
n, k=mi()
both=[0]
al=[0]
bob=[0]
for _ in range(n):
x, y, z=mi()
if y and z:
both.append(x)
elif y:
al.append(x)
elif z:
bob.append(x)
both.sort()
for i in range(1, len(both)):
both[i]+=both[i-1]
al.sort()
for i in range(1, len(al)):
al[i]+=al[i-1]
bob.sort()
for i in range(1, len(bob)):
bob[i]+=bob[i-1]
ans=1000000000000000000000000000
#print(both)
#print(al)
#print(bob)
for i in range(len(both)):
if len(al)>k-i and len(bob)>k-i:
ans=min(ans, both[i]+al[k-i]+bob[k-i])
#print(both[:i]+al[:k-i]+bob[:k-i])
if i==k:
ans=min(ans, both[i])
break
#print(ans)
print(-1 if ans==1000000000000000000000000000 else ans)
| 11 | PYTHON3 |
def cumsum(x):
n = len(x)
ans = [0]*(n+1)
for i in range(n):
ans[i+1]=ans[i]+x[i]
return ans
def solve(k, t, a, b):
n = len(t)
b10, b01, b11=[],[],[]
for i in range(n):
if (a[i]==1 and b[i]==1):
b11.append(t[i])
elif a[i]==1:
b10.append(t[i])
elif b[i]==1:
b01.append(t[i])
b10=sorted(b10)
b01=sorted(b01)
b11=sorted(b11)
b1 = [b10[i] + b01[i] for i in range(min(len(b10), len(b01)))]
cs_b1 = cumsum(b1)
cs_b11 = cumsum(b11)
if len(b1) + len(b11) < k:
return -1
ans=1e100
for i in range(0, k+1):
if i<=len(b1) and k-i<=len(b11):
ans = min(ans, cs_b1[i] + cs_b11[k-i])
return ans
n, k = map(int, input().split())
a,b,t = [0]*n,[0]*n,[0]*n
for i in range(n):
t[i], a[i], b[i] = map(int, input().split())
print(solve(k, t,a,b)) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
const ll N = 3e5 + 10;
const ll INF = 1e10;
const ll M = 1e3 + 1;
const ll L = 31;
const ll mod = 998244353;
ll solve() {
ll n, k;
cin >> n >> k;
ll t, a, b;
ll ans = 0;
multiset<ll> alice, bob, both;
for (ll i = 0; i < n; i++) {
cin >> t >> a >> b;
if (a == 1 && b == 1) {
both.insert(t);
} else if (a == 1) {
alice.insert(t);
} else if (b == 1) {
bob.insert(t);
}
}
while (both.size() > 0 && alice.size() > 0 && bob.size() > 0 && k > 0) {
ll a = *(alice.begin());
ll b = *(bob.begin());
ll c = *(both.begin());
if (a + b < c) {
ans += (a + b);
alice.erase(alice.begin());
bob.erase(bob.begin());
} else {
ans += c;
both.erase(both.begin());
}
k--;
}
if (k == 0) {
cout << ans << '\n';
return 0;
} else {
if (alice.size() == 0 || bob.size() == 0) {
if (both.size() < k) {
cout << -1 << '\n';
} else {
while (k > 0) {
ans += (*(both.begin()));
both.erase(both.begin());
k--;
}
cout << ans << '\n';
return 0;
}
} else {
if (alice.size() < k || bob.size() < k) {
cout << -1 << '\n';
return 0;
} else {
while (k > 0) {
ans += (*(alice.begin()));
alice.erase(alice.begin());
ans += (*(bob.begin()));
bob.erase(bob.begin());
k--;
}
cout << ans << '\n';
return 0;
}
}
}
return 0;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
solve();
return 0;
}
| 11 | CPP |
import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics
def sin():
return input()
def ain():
return list(map(int, sin().split()))
def sain():
return input().split()
def iin():
return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007
def readTree(n, m):
adj = [deque([]) for _ in range(n+1)]
for _ in range(m):
u,v = ain()
adj[u].append(v)
adj[v].append(u)
return adj
def main():
n, k = ain()
d = deque([])
a = 0
b = 0
for _ in range(n):
x = ain()
if x[1] == 1:
a += 1
if x[2] == 1:
b += 1
d.append(x)
if a < k or b < k:
print(-1)
else:
both = deque([])
a = deque([])
b = deque([])
for i in range(n):
if d[i][1] == 1 and d[i][2] == 1:
both.append(d[i][0])
elif d[i][1] == 1 and d[i][2] == 0:
a.append(d[i][0])
elif d[i][1] == 0 and d[i][2] == 1:
b.append(d[i][0])
a = sorted(a)
b = sorted(b)
for i in range(min(len(a), len(b))):
both.append(a[i]+b[i])
both = sorted(both)
print(sum(both[0:k]))
# Fast IO Template starts
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")
# Fast IO Template ends
if __name__ == "__main__":
main()
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
void printVector(vector<string> &v) {
for (auto x : v) cout << x << "\n";
}
void printVector(vector<int> &v) {
for (auto x : v) cout << x << " ";
cout << "\n";
}
int main() {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
int t;
t = 1;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> v1, v2, v3;
int ca = 0, cb = 0;
for (int i = 0; i < n; i++) {
int tm, a, b;
cin >> tm >> a >> b;
if (a == 1) {
ca++;
if (b == 1) {
v3.push_back(tm);
cb++;
} else {
v1.push_back(tm);
}
} else if (b == 1) {
v2.push_back(tm);
cb++;
}
}
if (ca < k || cb < k) {
cout << -1 << "\n";
continue;
}
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
sort(v3.begin(), v3.end());
int i1 = 0, i2 = 0, i3 = 0;
int c1 = 0, c2 = 0;
int ans = 0;
while (c1 < k || c2 < k) {
if (c1 < k && c2 < k) {
int t1 = 2e4 + 1;
if (i1 < v1.size()) t1 = v1[i1];
int t2 = 2e4 + 1;
if (i2 < v2.size()) t2 = v2[i2];
int t3 = 2e4 + 1;
if (i3 < v3.size()) t3 = v3[i3];
if (t3 <= (t1 + t2)) {
ans += t3;
c1++;
c2++;
i3++;
} else {
ans += t1;
ans += t2;
c1++;
c2++;
i1++;
i2++;
}
} else if (c1 < k) {
int t1 = 2e4 + 1;
if (i1 < v1.size()) t1 = v1[i1];
int t3 = 2e4 + 1;
if (i3 < v3.size()) t3 = v3[i3];
if (t3 <= t1) {
ans += t3;
c1++;
c2++;
i3++;
} else {
ans += t1;
c1++;
i1++;
}
} else {
int t2 = 2e4 + 1;
if (i2 < v2.size()) t2 = v2[i2];
int t3 = 2e4 + 1;
if (i3 < v3.size()) t3 = v3[i3];
if (t3 <= t2) {
ans += t3;
c1++;
c2++;
i3++;
} else {
ans += t2;
c2++;
i2++;
}
}
}
cout << ans << "\n";
}
}
| 11 | CPP |
n,k=list(map(int,input().split()))
both=[]
alice=[]
bob=[]
for i in range(n):
t,a,b=list(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)
both.sort();alice.sort();bob.sort()
x=0;y=0
if len(both)+len(alice)<k or len(both)+len(bob)<k:
print(-1)
else:
both.append(10**9);alice.append(10**9);bob.append(10**9)
i = 0;
j = 0
time=0
alpha=0
while x<k and y<k:
if i<len(both) and j<len(alice) and alpha<len(bob):
if both[i]<=alice[j]+bob[alpha]:
time+=both[i]
i+=1
x+=1;y+=1
else:
time+=alice[j]+bob[alpha]
j+=1
alpha+=1
x+=1;y+=1
else:
if len(both)!=i:
if len(alice)==0:
if len(bob)==0:
time+=both[i]
i+=1
x+=1;y+=1
print(time)
| 11 | PYTHON3 |
from sys import stdin, stdout
from sys import maxsize
#input = stdin.readline().strip
from functools import cmp_to_key
def solve(books, k):
alice = []
bob = []
both = []
for book in books:
if(book[1] == 1 and book[2] == 1):
both.append(book[0])
elif(book[1] == 0 and book[2] == 1):
bob.append(book[0])
elif(book[1] == 1 and book[2] == 0):
alice.append(book[0])
alice.sort(reverse=True)
bob.sort(reverse=True)
both.sort(reverse=True)
no_of_books, time = 0, 0
while(len(alice) != 0 and len(bob) != 0 and len(both) != 0 and no_of_books < k):
no_of_books += 1
if(alice[-1]+bob[-1] < both[-1]):
time += alice[-1]+bob[-1]
alice.pop()
bob.pop()
else:
time += both[-1]
both.pop()
while(len(both) != 0 and no_of_books < k):
no_of_books += 1
time += both[-1]
both.pop()
while(len(alice) != 0 and len(bob) != 0 and no_of_books < k):
no_of_books += 1
time += alice[-1]+bob[-1]
alice.pop()
bob.pop()
if(no_of_books == k):
return time
else:
return -1
test = 1
# test = int(input())
for t in range(0, test):
# brr = [list(map(int,input().split())) for i in range(rows)] # 2D array row-wise input
# n = int(input())
# s = list(input()) # String Input, converted to mutable list.
n, k = list(map(int, input().split()))
# arr = [int(x) for x in input().split()]
b = [tuple(map(int, input().split())) for i in range(n)]
ans = solve(b, k)
print(ans)
'''
rows, cols = (5, 5)
arr = [[0]*cols for j in range(rows)] # 2D array initialization
b=input().split() # list created by spliting about spaces
brr = [[int(b[cols*i+j]) for j in range(cols)] for i in range(rows)] # 2D array Linear Input
rows,cols=len(brr),len(brr[0]) # no of rows/cols for 2D array
arr.sort(key = lambda x : x[1]) # sort list of tuples by 2nd element, Default priority - 1st Element then 2nd Element
s=set() # empty set
a=maxsize # initializing infinity
b=-maxsize # initializing -infinity
mapped=list(map(function,input)) # to apply function to list element-wise
try: # Error handling
#code 1
except: # ex. to stop at EOF
#code 2 , if error occurs
'''
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
long long time(vector<int> l, int il, vector<int> b, int ib, vector<int> r,
int ir, int k) {
long long ans = 0;
int left = k, right = k;
int index_both = 0;
int index_right = 0;
int index_left = 0;
while (left != 0 && right != 0) {
if (index_both == ib) {
if (index_right == ir || index_left == il) {
return -1;
} else {
ans += l[index_left];
ans += r[index_right];
index_left++;
index_right++;
left--;
right--;
}
} else {
if (index_right == ir || index_left == il) {
ans += b[index_both];
index_both++;
left--;
right--;
} else {
long long b1 = b[index_both];
long long t1 = l[index_left] + r[index_right];
if (b1 <= t1) {
ans += b1;
index_both++;
left--;
right--;
} else {
ans += t1;
index_left++;
index_right++;
left--;
right--;
}
}
}
}
while (left > 0) {
if (index_both == ib) {
if (index_left == il)
return -1;
else {
ans += l[index_left];
index_left++;
left--;
}
} else {
if (index_left == il) {
ans += b[index_both];
index_both++;
left--;
} else {
long long b1 = b[index_both];
long long l1 = l[index_left];
if (b1 <= l1) {
ans += b1;
index_both++;
left--;
} else {
ans += l1;
index_left++;
left--;
}
}
}
}
while (right > 0) {
if (index_both == ib) {
if (index_right == ir)
return -1;
else {
ans += r[index_right];
index_right++;
right--;
}
} else {
if (index_right == ir) {
ans += b[index_both];
index_both++;
right--;
} else {
long long b1 = b[index_both];
long long r1 = r[index_right];
if (b1 <= r1) {
ans += b1;
index_both++;
right--;
} else {
ans += r1;
index_right++;
right--;
}
}
}
}
return ans;
}
int main() {
int n, k;
cin >> n >> k;
vector<int> l(n);
vector<int> r(n);
vector<int> b(n);
int ib = 0, il = 0, ir = 0;
int t, ai, bi;
for (int i = 0; i < n; i++) {
cin >> t >> ai >> bi;
if (ai == 1 && bi == 1) {
b[ib] = t;
ib++;
} else if (ai == 1) {
l[il] = t;
il++;
} else if (bi == 1) {
r[ir] = t;
ir++;
}
}
vector<int>::iterator it = l.begin();
advance(it, il);
sort(l.begin(), it);
it = r.begin();
advance(it, ir);
sort(r.begin(), it);
it = b.begin();
advance(it, ib);
sort(b.begin(), it);
cout << time(l, il, b, ib, r, ir, k) << '\n';
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
long long power(long long x, long long y, long long p) {
long long res = 1;
x = x % p;
while (y > 0) {
if (y & 1) res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
inline long long add(long long a, long long b) { return (a + b) % 1000000007; }
inline long long mul(long long a, long long b) { return (a * b) % 1000000007; }
long long f[4000010], iv[4000010];
long long C(long long n, long long r) {
return mul(f[n], mul(iv[r], iv[n - r]));
}
void prep_fac() {
f[0] = 1;
for (int i = 1; i < 4000010; i++) f[i] = mul(i, f[i - 1]);
iv[4000010 - 1] = power(f[4000010 - 1], 1000000007 - 2, 1000000007);
for (long long i = 4000010 - 2; i >= 0; --i) iv[i] = mul(i + 1, iv[i + 1]);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, k;
cin >> n >> k;
int c1 = 0, c2 = 0;
vector<long long> v[4];
v[1].push_back(0), v[2].push_back(0), v[3].push_back(0);
for (int i = 0; i < n; i++) {
int t, a, b;
cin >> t >> a >> b;
v[2 * a + b].push_back(t);
}
for (int i = 1; i < 4; i++) {
sort(v[i].begin(), v[i].end());
for (int j = 1; j < v[i].size(); j++) {
v[i][j] += v[i][j - 1];
}
}
long long ans = INT_MAX;
for (int i = 0; i < v[3].size(); i++) {
if (v[2].size() > k - i && v[1].size() > k - i)
ans = min(v[3][i] + v[2][k - i] + v[1][k - i], ans);
}
if (ans == INT_MAX) ans = -1;
cout << ans;
}
| 11 | CPP |
import sys
input = sys.stdin.readline
n,k=map(int,input().split())
BOOKS=[tuple(map(int,input().split())) for i in range(n)]
A=[]
B=[]
AB=[]
for t,a,b in BOOKS:
if a==1 and b==1:
AB.append(t)
if a==1 and b==0:
A.append(t)
if a==0 and b==1:
B.append(t)
A.sort()
B.sort()
AB.sort()
from itertools import accumulate
SA=[0]+list(accumulate(A))
SB=[0]+list(accumulate(B))
SAB=[0]+list(accumulate(AB))
ANS=1<<31
for i in range(len(SAB)):
if 0<=k-i<len(SA) and 0<=k-i<len(SB):
ANS=min(ANS,SAB[i]+SA[k-i]+SB[k-i])
if ANS==1<<31:
print(-1)
else:
print(ANS)
| 11 | PYTHON3 |
n,k=[int(x) for x in input().split(' ')]
time=[]
a=[]
b=[]
for i in range(n):
p,q,r=[int(x) for x in input().split(' ')]
time.append(p)
a.append(q)
b.append(r)
oa=[]
ob=[]
bo=[]
no=[]
for i in range(n):
if(a[i] and b[i]):
bo.append(i)
elif(a[i] and b[i]==0):
oa.append(i)
elif(a[i]==0 and b[i]):
ob.append(i)
else:
no.append(i)
if((len(bo)+len(oa)<k) or (len(bo)+len(ob)<k)):
print(-1)
else:
def time_req(i):
return(time[i])
oa.sort(key=time_req)
ob.sort(key=time_req)
bo.sort(key=time_req)
oa.reverse()
ob.reverse()
bo.reverse()
books=set()
for i in range(k):
if(len(oa)==0 or len(ob)==0):
books.add(bo.pop())
continue
elif(len(bo)==0):
books.add(oa.pop())
books.add(ob.pop())
continue
if(time[bo[-1]]<(time[oa[-1]]+time[ob[-1]]) or len(oa)==0 or len(ob)==0):
books.add(bo.pop())
else:
books.add(oa.pop())
books.add(ob.pop())
print(sum(list(map(time_req,list(books))))) | 11 | PYTHON3 |
from sys import stdin
inp = lambda : stdin.readline().strip()
n, k = [int(x) for x in inp().split()]
b = []
for _ in range(n):
b.append([int(x) for x in inp().split()])
both = []
alice = []
bob = []
for i in b:
if i[1] == 1 and i[2] == 1:
both.append(i[0])
elif i[1] == 1:
alice.append(i[0])
elif i[2] == 1:
bob.append(i[0])
if len(alice)+len(both) < k or len(bob) + len(both) <k:
print(-1)
exit()
both.sort()
alice.sort()
bob.sort()
b = 0
a = 0
bb = 0
cost = 0
liked = 0
minimum = min(len(alice),len(bob))
x = max(k-minimum,0)
for i in range(x):
if liked == k:
print(cost)
exit()
cost += both[i]
b += 1
liked += 1
while True:
if liked == k:
print(cost)
break
if b < len(both) and a<len(alice) and bb<len(bob) and both[b] <= alice[a] + bob[bb]:
cost += both[b]
b += 1
liked += 1
else:
cost += alice[a] + bob[bb]
bb += 1
a += 1
liked += 1 | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k, i, ok, s = 0, sum = 0, ans = 0;
multiset<long long> pi1;
vector<long long> pi2, pi3;
multimap<long long, long long>::iterator it;
cin >> n >> ok;
long long a, b, c;
for (i = 0; i < n; i++) {
cin >> a >> b >> c;
if (b == 1 && c == 1) {
pi1.insert(a);
s++;
sum++;
} else if (b == 1) {
pi2.push_back(a);
s++;
} else if (c == 1) {
pi3.push_back(a);
sum++;
}
}
sort(pi2.begin(), pi2.end());
sort(pi3.begin(), pi3.end());
long long l = min(pi2.size(), pi3.size());
if (s < ok || sum < ok)
cout << "-1" << endl;
else {
for (i = 0; i < l; i++) {
pi1.insert(pi2[i] + pi3[i]);
}
long long ans1 = 0;
for (auto kk : pi1) {
ans1 += kk;
ok--;
if (ok == 0) break;
}
cout << ans1 << endl;
}
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
scanf("%d %d", &n, &k);
long long ans = 0;
priority_queue<int, vector<int>, greater<int>> q1, q2, q3;
int ct1 = 0;
int ct2 = 0;
for (int i = 1; i <= n; i++) {
long long t;
int a, b;
scanf("%lld %d %d", &t, &a, &b);
if (a == 1) ct1++;
if (b == 1) ct2++;
if (a == 1 && b == 0) {
q1.push(t);
}
if (a == 0 && b == 1) {
q2.push(t);
}
if (a == 1 && b == 1) {
q3.push(t);
}
}
int hehe = min(ct1, ct2);
if (hehe < k) {
printf("-1");
return 0;
}
for (int kk = 1; kk <= k; kk++) {
if (!q1.empty() && !q2.empty()) {
int now = q1.top() + q2.top();
if (!q3.empty()) {
int now2 = q3.top();
if (now < now2) {
ans += now;
q1.pop();
q2.pop();
} else {
ans += now2;
q3.pop();
}
} else {
ans += now;
q1.pop();
q2.pop();
}
} else {
if (!q3.empty()) {
int now2 = q3.top();
ans += now2;
q3.pop();
}
}
}
printf("%lld\n", ans);
return 0;
}
| 11 | CPP |
n, k = map(int, input().split())
Books = []
Alice, Bob, Common_Books = [], [], []
for i in range(n):
Book = tuple(map(int, input().split()))
Books.append(Book)
Books = sorted(Books, key=lambda x:x[0])
# print(Books)
for Book in Books:
if Book[1] == 1 and Book[2] == 1:
if len(Common_Books) < k:
Common_Books.append(Book)
else:
break
else:
if len(Alice) != k and Book[1] == 1:
Alice.append(Book)
if len(Bob) != k and Book[2] == 1:
Bob.append(Book)
t = len(Common_Books)
if len(Alice) < k-t or len(Bob) < k-t:
print(-1)
else:
# print(Common_Books)
# print(Alice, Bob)
Min_time = 0
a, iab, ic = 0, 0, 0
while(a<k):
if iab < len(Alice):
A = Alice[iab]
else:
A = (float('inf'), 0, 0)
if iab < len(Bob):
B = Bob[iab]
else:
B = (float('inf'), 0, 0)
if ic < len(Common_Books):
C = Common_Books[ic]
else:
C = (float('inf'), 0, 0)
if A[0]+B[0] < C[0]:
Min_time += A[0]+B[0]
iab += 1
else:
Min_time += C[0]
ic += 1
a += 1
print(Min_time)
| 11 | PYTHON3 |
z=input
mod = 10**9 + 7
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
def lcd(xnum1,xnum2):
return (xnum1*xnum2//gcd(xnum1,xnum2))
################################################################################
"""
n=int(z())
for _ in range(int(z())):
x=int(z())
l=list(map(int,z().split()))
n=int(z())
l=sorted(list(map(int,z().split())))[::-1]
a,b=map(int,z().split())
l=set(map(int,z().split()))
led=(6,2,5,5,4,5,6,3,7,6)
vowel={'a':0,'e':0,'i':0,'o':0,'u':0}
color-4=["G", "GB", "YGB", "YGBI", "OYGBI" ,"OYGBIV",'ROYGBIV' ]
"""
###########################---START-CODING---###############################################
for _ in range(1):
n,k=map(int,z().split())
a=[]
b=[]
them=[]
ta,tb,th=0,0,0
for _ in range(n):
c,d,e=map(int,z().split())
if d==1 and e==1:
them.append(c)
th+=1
continue
if d==1:
a.append(c)
ta+=1
continue
if e==1:
b.append(c)
tb+=1
a=sorted(a)
b=sorted(b)
them=sorted(them)
for i in range(min(ta,tb)):
them.append(a[i]+b[i])
if len(them)<k:
print(-1)
else:
them=sorted(them)
print(sum(them[:k]))
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int n, k, m, x, y, z;
int ans;
vector<int> a[2][2];
vector<pair<int, int> > f[2][2];
int id[2][2];
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &x, &y, &z);
a[y][z].push_back(x);
f[y][z].push_back({x, i + 1});
}
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++) {
sort(a[i][j].begin(), a[i][j].end());
a[i][j].push_back(1000000);
sort(f[i][j].begin(), f[i][j].end());
}
int ans = -1, sum = 0, u = 0;
while (u < a[1][1].size()) {
if (u > m) {
u++;
continue;
}
int r = max(k - u, 0);
if (r >= a[1][0].size() || r >= a[0][1].size()) {
u++;
continue;
}
if ((u + 2 * r) > m) {
u++;
continue;
}
if (a[1][0].size() + a[0][1].size() + a[0][0].size() + u < m + 3) {
u++;
continue;
}
break;
}
if (u >= a[1][1].size()) {
cout << -1;
return 0;
}
int r = max(k - u, 0);
int s1 = r, s2 = r, s3 = 0;
while (u + s1 + s2 + s3 < m) {
int d = min(min(a[1][0][s1], a[0][1][s2]), a[0][0][s3]);
if (d > 10000) {
cout << -1;
return 0;
}
if (d == a[1][0][s1]) {
s1++;
continue;
}
if (d == a[0][1][s2]) {
s2++;
continue;
}
if (d == a[0][0][s3]) {
s3++;
continue;
}
}
for (int i = 0; i < u; i++) sum += a[1][1][i];
for (int i = 0; i < s1; i++) sum += a[1][0][i];
for (int i = 0; i < s2; i++) sum += a[0][1][i];
for (int i = 0; i < s3; i++) sum += a[0][0][i];
ans = sum;
int q1 = s1, q2 = s2, q3 = s3, q4 = u;
s1--;
s2--;
s3--;
while (u + 1 < a[1][1].size()) {
sum += a[1][1][u];
u++;
if (s1 == -1 && s2 == -1 && s3 == -1) break;
int d = 0, pp = 0;
if ((s1 != -1)) {
d += a[1][0][s1];
pp++;
s1--;
}
if ((s2 != -1)) {
d += a[0][1][s2];
pp++;
s2--;
}
if ((s3 != -1)) {
d += a[0][0][s3];
pp++;
s3--;
}
sum -= d;
for (int i = 0; i < pp - 1; i++) {
int gg = min(min(a[1][0][s1 + 1], a[0][1][s2 + 1]), a[0][0][s3 + 1]);
if (gg > 10000) {
cout << -1;
return 0;
}
if (gg == a[1][0][s1 + 1]) {
sum += a[1][0][s1 + 1];
s1++;
continue;
}
if (gg == a[0][1][s2 + 1]) {
sum += a[0][1][s2 + 1];
s2++;
continue;
}
if (gg == a[0][0][s3 + 1]) {
sum += a[0][0][s3 + 1];
s3++;
continue;
}
}
if (sum < ans) {
ans = sum;
q4 = u;
q3 = s3 + 1;
q2 = s2 + 1;
q1 = s1 + 1;
}
}
printf("%d\n", ans);
for (int i = 0; i < q4; i++) printf("%d ", f[1][1][i].second);
for (int i = 0; i < q3; i++) printf("%d ", f[0][0][i].second);
for (int i = 0; i < q2; i++) printf("%d ", f[0][1][i].second);
for (int i = 0; i < q1; i++) printf("%d ", f[1][0][i].second);
return 0;
}
| 11 | CPP |
n,k=map(int,input().split())
alice=[]
bob=[]
both=[]
a,b=0,0
al,bl,bol=0,0,0
for i in range(n):
t,x,y=map(int,input().split())
if x==1 and y==1:
both.append(t)
bol+=1
elif x==1:
alice.append(t)
al+=1
elif y==1:
bob.append(t)
bl+=1
alice.sort()
bob.sort()
both.sort()
ai,bi,boi=0,0,0
count=0
check=False
while ((ai<al and bi<bl) and boi<bol):
if both[boi]<alice[ai]+bob[bi]:
a+=1
b+=1
count+=both[boi]
boi+=1
else:
count+=alice[ai]+bob[bi]
ai+=1
bi+=1
a+=1
b+=1
if a>=k and b>=k:
check=True
break
if check:
print(count)
else:
if boi==bol:
na=k-a
if al-ai>=na:
for i in range(max(na,0)):
count+=alice[ai+i]
nb=k-b
if bl-bi>=nb:
for i in range(max(nb,0)):
count+=bob[bi+i]
print(count)
else:
print("-1")
else:
print('-1')
elif ai==al:
na=k-a
if bol-boi>=na:
for i in range(max(na,0)):
count+=both[boi+i]
b+=1
nb=k-b
if bl+bol-boi-bi>=nb:
l=[]
for i in range(boi,min(bol,boi+max(nb,0))):
l.append(both[i])
for i in range(bi,min(bl,bi+max(nb,0))):
l.append(bob[i])
l.sort()
for i in range(max(nb,0)):
count+=l[i]
print(count)
else:
print("-1")
else:
print("-1")
else:
nb=k-b
if bol-boi>=nb:
for i in range(max(nb,0)):
count+=both[boi+i]
a+=1
na=k-a
if al+bol-boi-ai>=na:
l=[]
for i in range(boi,min(bol,boi+max(na,0))):
l.append(both[i])
for i in range(ai,min(al,ai+max(na,0))):
l.append(alice[i])
l.sort()
for i in range(max(na,0)):
count+=l[i]
print(count)
else:
print("-1")
else:
print('-1') | 11 | PYTHON3 |
from sys import stdin, stdout
from sys import maxsize
#input = stdin.readline().strip
from functools import cmp_to_key
def solve(books, k):
alice = []
bob = []
both = []
for book in books:
if(book[1] == 1 and book[2] == 1):
both.append(book[0])
elif(book[1] == 0 and book[2] == 1):
bob.append(book[0])
elif(book[1] == 1 and book[2] == 0):
alice.append(book[0])
alice.sort(reverse=True)
bob.sort(reverse=True)
both.sort(reverse=True)
no_of_books, time = 0, 0
while(len(alice) != 0 and len(bob) != 0 and len(both) != 0 and no_of_books < k):
no_of_books += 1
if(alice[-1]+bob[-1] < both[-1]):
time += alice[-1]+bob[-1]
alice.pop()
bob.pop()
else:
time += both[-1]
both.pop()
while(len(both) != 0 and no_of_books < k):
no_of_books += 1
time += both[-1]
both.pop()
while(len(alice) != 0 and len(bob) != 0 and no_of_books < k):
no_of_books += 1
time += alice[-1]+bob[-1]
alice.pop()
bob.pop()
if(no_of_books == k):
return time
else:
return -1
test = 1
# test = int(input())
for t in range(0, test):
# brr = [list(map(int,input().split())) for i in range(rows)] # 2D array row-wise input
# n = int(input())
# s = list(input()) # String Input, converted to mutable list.
n, k = list(map(int, input().split()))
# arr = [int(x) for x in input().split()]
b = [tuple(map(int, input().split())) for i in range(n)]
ans = solve(b, k)
print(ans)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << '\n';
err(++it, args...);
}
long long powMod(long long x, long long y) {
long long p = 1;
while (y) {
if (y % 2) {
p = (p * x) % ((long long)1e9 + 7);
}
y /= 2;
x = (x * x) % ((long long)1e9 + 7);
}
return p;
}
long long CpowMod(long long x, long long y, long long w) {
long long p = 1;
while (y) {
if (y % 2) {
p = (p * x) % w;
}
y /= 2;
x = (x * x) % w;
}
return p;
}
long long invMod(long long x) { return powMod(x, ((long long)1e9 + 7) - 2); }
long long CinvMod(long long x, long long w) { return CpowMod(x, w - 2, w); }
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
void solve() {
long long n, k;
cin >> n >> k;
multiset<long long> q1, q2, qq, q3, q4;
for (int i = 0; i <= n - 1; i++) {
long long x, y, t;
cin >> t >> x >> y;
if (x == 1 && y == 1) {
qq.insert(t);
} else if (x == 1) {
q1.insert(t);
} else if (y == 1) {
q2.insert(t);
}
}
if ((long long)qq.size() + (long long)q1.size() < k ||
(long long)qq.size() + (long long)q2.size() < k) {
cout << -1;
return;
}
long long mb = min((long long)qq.size() - 1, k - 1);
for (int i = 0; i <= mb; i++) {
auto it = *qq.begin();
q3.insert(it);
qq.erase(qq.find(it));
}
long long ap = k - (long long)q3.size();
{};
for (int i = 0; i <= ap - 1; i++) {
auto it1 = *q1.begin();
auto it2 = *q2.begin();
q4.insert(it1);
q4.insert(it2);
q1.erase(q1.find(it1));
q2.erase(q2.find(it2));
}
while ((long long)q3.size() && (long long)q1.size() && (long long)q2.size()) {
auto it1 = *q1.begin();
auto it2 = *q2.begin();
auto it3 = *q3.rbegin();
if (it1 + it2 < it3) {
q4.insert(it1);
q4.insert(it2);
q1.erase(q1.find(it1));
q2.erase(q2.find(it2));
q3.erase(q3.find(it3));
} else {
break;
}
}
long long sum = 0;
for (auto &it : q3) {
sum += it;
}
for (auto &it : q4) {
sum += it;
}
cout << sum;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cout.precision(20);
solve();
return 0;
}
| 11 | CPP |
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
n,k=map(int,input().split())
a1=[]
b1=[]
x=set()
y=set()
com=[]
for i in range(n):
t,a,b=map(int,input().split())
if a==1 and b!=1:
a1.append(t)
if b==1 and a!=1:
b1.append(t)
if a==1 and b==1:
com.append(t)
s=set()
count=0
a1.sort(reverse=True)
b1.sort(reverse=True)
com.sort(reverse=True)
a=k
b=k
# print(com,a1,b1)
if len(a1)+len(com)<k or len(b1)+len(com)<k:
print(-1)
exit()
while a>0 or b>0:
if a>0 and b>0:
if len(com)>0:
if len(a1)>0 and len(b1)>0:
if a1[-1]+b1[-1]<com[-1]:
count+=a1.pop()+b1.pop()
a-=1
b-=1
else:
count+=com.pop()
a-=1
b-=1
else:
count+=com.pop()
a-=1
b-=1
else:
count+=a1.pop()+b1.pop()
a-=1
b-=1
else:
if len(com)>0:
if a>0:
if len(a1)>0 and a1[-1]<com[-1]:
count+=a1.pop()
a-=1
else:
count+=com.pop()
a-=1
b-=1
else:
if len(b1)>0 and b1[-1]<com[-1]:
count+=a1.pop()
b-=1
else:
count+=com.pop()
a-=1
b-=1
else:
if a>0:
count+=a1.pop()
a-=1
else:
count+=b1.pop()
b-=1
# print(a,b)
print(count)
| 11 | PYTHON3 |
n, k = map(int, input().split())
lBoth = []
lAlice = []
lBob = []
for i in range(n):
t, a, b = map(int, input().split())
if a == 1 and b == 1:
lBoth.append(t)
elif a == 1:
lAlice.append(t)
elif b == 1:
lBob.append(t)
if len(lBoth) + min(len(lAlice), len(lBob)) < k:
print(-1)
else:
lBob.sort()
lAlice.sort()
lBoth.sort()
numP = 0
numB = 0
kol = 0
tm = 0
while kol < k:
if numP == len(lAlice) or numP == len(lBob):
tm += sum(lBoth[numB:numB + k - kol])
break
if numB == len(lBoth):
tm += sum(lBob[numP:numP + k - kol]) + sum(lAlice[numP:numP + k - kol])
break
if lBob[numP] + lAlice[numP] < lBoth[numB]:
tm += lAlice[numP] + lBob[numP]
numP += 1
kol += 1
else:
tm += lBoth[numB]
numB += 1
kol += 1
print(tm)
| 11 | PYTHON3 |
n, k = [int(i) for i in input().split()]
arr = []
for i in range(n):
arr.append([int(i) for i in input().split()])
one_one = []
zero_one = []
one_zero = []
for i in arr:
if i[2] == i[1] == 1:
one_one.append(i[0])
elif i[1] == 1:
one_zero.append(i[0])
elif i[2] == 1:
zero_one.append(i[0])
one_one.append(10**20)
one_zero.append(10**20)
zero_one.append(10**20)
one_one.sort()
zero_one.sort()
one_zero.sort()
ptr1 = ptr2 = ptr3 = 0
n1 = 0
ans = 0
while n1 < k:
if one_one[ptr1] < one_zero[ptr2] + zero_one[ptr3]:
ans += one_one[ptr1]
ptr1 += 1
n1 += 1
else:
ans += one_zero[ptr2] + zero_one[ptr3]
ptr2 += 1
ptr3 += 1
n1 += 1
if ans >= 10**20:
ans = -1
break
print(ans)
| 11 | PYTHON3 |
n, k = map(int, input().split())
arr = [[int(i) for i in input().split()] for _ in range(n)]
a = sorted([arr[i][0] for i in range(n) if arr[i][1] == 1 and arr[i][2] == 0])
b = sorted([arr[i][0] for i in range(n) if arr[i][1] == 0 and arr[i][2] == 1])
ab = sorted([arr[i][0] for i in range(n) if arr[i][1] == 1 and arr[i][2] == 1])
ans = 0
l, r = 0, 0
for i in range(k):
v1 = 10 ** 9
if len(a) > l and len(b) > l:
v1 = a[l] + b[l]
v2 = 10 ** 9
if len(ab) > r:
v2 = ab[r]
if v1 == v2 == 10 ** 9:
ans = -1
break
if v1 < v2:
l += 1
ans += v1
else:
r += 1
ans += v2
print(ans)
| 11 | PYTHON3 |
from collections import defaultdict
n, k = list(map(int, input().split()))
arr = []
for i in range(n):
temp = list(map(int, input().split()))
arr.append(temp)
d = defaultdict(list)
for i in range(len(arr)):
ti, ai, bi = arr[i]
if ai == 1 and bi == 1:
if '11' in d.keys():
d['11'].append(ti)
else:
d['11'] = [ti]
elif ai == 0 and bi == 1:
if '01' in d.keys():
d['01'].append(ti)
else:
d['01'] = [ti]
elif ai == 1 and bi == 0:
if '10' in d.keys():
d['10'].append(ti)
else:
d['10'] = [ti]
# print(d)
smallest_one = min(len(d['01']), len(d['10']))
two = len(d['11'])
for i in d.keys():
d[i] = sorted(d[i])
# for i in d.keys():
# sum_ = 0
# for j in range(len(d[i])):
# sum_ += d[i][j]
# d[i][j] = sum_
ans = 0
l1 = 0
l2 = 0
current_k = 0
while l1 < two and l2 < smallest_one and current_k < k:
if d['11'][l1] <= (d['01'][l2] + d['10'][l2]):
ans += d['11'][l1]
l1 += 1
else:
ans += d['01'][l2] + d['10'][l2]
l2 += 1
current_k += 1
if current_k != k and l1 < two:
while l1 < two and current_k < k:
ans += d['11'][l1]
l1 += 1
current_k += 1
elif current_k != k and l2 < smallest_one:
while l2 < smallest_one and current_k < k:
ans += d['01'][l2] + d['10'][l2]
l2 += 1
current_k += 1
if current_k == k:
print(ans)
else:
print(-1)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n, i, j, k, t, p, q;
cin >> n >> k;
multiset<long long> a, b, d;
long long al = 0, bl = 0;
for (i = 0; i < n; i++) {
cin >> t >> p >> q;
if (p && q) {
d.insert(t);
al++;
bl++;
} else if (p) {
a.insert(t);
al++;
} else if (q) {
b.insert(t);
bl++;
}
}
if (al < k || bl < k) {
cout << -1 << "\n";
return 0;
}
al = k, bl = k;
long long ans = 0;
auto ita = a.begin();
auto itb = b.begin();
auto itd = d.begin();
while (al > 0 || bl > 0) {
if (al > 0 && bl > 0) {
if (ita == a.end() || itb == b.end()) {
ans += *itd;
itd++;
al--;
bl--;
} else {
if (itd != d.end()) {
if (*ita + *itb < *itd) {
ans += *ita + *itb;
ita++;
itb++;
al--;
bl--;
} else {
ans += *itd;
itd++;
al--;
bl--;
}
} else {
ans += *ita + *itb;
ita++;
itb++;
al--;
bl--;
}
}
} else if (al > 0) {
if (ita == a.end()) {
ans += *itd;
itd++;
al--;
bl--;
} else if (itd == d.end()) {
ans += *ita;
al--;
ita++;
} else {
if (*ita < *itd) {
ans += *ita;
al--;
ita++;
} else {
ans += *itd;
itd++;
al--;
bl--;
}
}
} else if (bl > 0) {
if (itb == b.end()) {
ans += *itd;
itd++;
al--;
bl--;
} else if (itd == d.end()) {
ans += *itb;
bl--;
itb++;
} else {
if (*itb < *itd) {
ans += *itb;
bl--;
itb++;
} else {
ans += *itd;
itd++;
al--;
bl--;
}
}
}
}
cout << ans << "\n";
return 0;
}
| 11 | CPP |
t,k = map(int,input().split())
A = []
B = []
C = []
for i in range(t):
a,b,c = map(int,input().split())
if b == 1 and c == 0:
A.append(a)
elif b == 0 and c == 1:
B.append(a)
elif b == 1:
C.append(a)
if min(len(A),len(B)) + len(C) < k:
print(-1)
else:
A.sort()
B.sort()
s = 0
for i in range(min(len(A),len(B))):
C.append(A[i] + B[i])
C.sort()
for i in range(k):
s += C[i]
print(s) | 11 | PYTHON3 |
n,k = map(int,input().split())
x = list()
y = list()
z = list()
for _ in range(n):
t,a,b = map(int,input().split())
if a == 0 and b == 0:
continue
elif a == 1 and b == 0:
x.append(t)
elif a == 0 and b == 1:
y.append(t)
else:
z.append(t)
x.sort()
y.sort()
for i in range(min(len(x),len(y))):
z.append(x[i] + y[i])
z.sort()
if len(z) < k:
print("-1")
else:
res = 0;
for i in range(0,k):
res += z[i];
print(res)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
vector<ll> L, R, M;
ll p(const vector<ll>& v, ll c) {
if (c <= 0) return 0;
return v[c - 1];
}
const ll INF = 5e10;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
ll N, K;
cin >> N >> K;
for (int i = 0; i < N; ++i) {
ll time, l, r;
cin >> time >> l >> r;
if ((l + r) == 2) {
M.push_back(time);
} else if (l + r == 1) {
if (l)
L.push_back(time);
else
R.push_back(time);
}
}
sort(L.begin(), L.end());
sort(R.begin(), R.end());
sort(M.begin(), M.end());
for (int i = 1; i < ((int)(L.size())); ++i) {
L[i] += L[i - 1];
}
for (int i = 1; i < ((int)(R.size())); ++i) {
R[i] += R[i - 1];
}
for (int i = 1; i < ((int)(M.size())); ++i) {
M[i] += M[i - 1];
}
ll ans = INF;
for (int m = 0; m <= ((int)(M.size())); ++m) {
ll LR = K - m;
if (((int)(L.size())) < LR || ((int)(R.size())) < LR) {
continue;
}
ll t = p(M, m) + p(L, LR) + p(R, LR);
ans = min(ans, t);
}
cout << (ans == INF ? -1 : ans);
return 0;
}
| 11 | CPP |
def func(n, k):
common = []
bob = []
alice = []
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)
if len(common)+len(alice) < k or len(common)+len(bob) < k:
print(-1)
return
common.sort()
alice.sort()
bob.sort()
c_num = min(k, len(common))
num = k-c_num
while c_num != 0 and num < len(alice) and num < len(bob) and common[c_num-1] > alice[num]+bob[num]:
c_num -= 1
num += 1
print(sum(common[:c_num])+sum(alice[:num])+sum(bob[:num]))
# cases = int(input())
for i in range(1):
n, k = map(int, input().split())
func(n, k)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
;
int n, k;
cin >> n >> k;
vector<int> t(n), a(n), b(n);
for (int i = 0; i < n; i++) cin >> t[i] >> a[i] >> b[i];
vector<vector<int>> elements(4);
for (int i = 0; i < n; i++) elements[2 * a[i] + b[i]].push_back(t[i]);
for (int i = 0; i < 4; i++) sort(elements[i].begin(), elements[i].end());
vector<vector<int>> prefix(4);
for (int i = 0; i < 4; i++) {
prefix[i].push_back(0);
for (auto &x : elements[i]) prefix[i].push_back(prefix[i].back() + x);
}
int ans = INT_MAX;
for (int i = 0; i <= min((int)elements[3].size(), k); i++) {
int req = k - i;
if (prefix[1].size() <= req || prefix[2].size() <= req) continue;
int cur = prefix[1][req] + prefix[2][req] + prefix[3][i];
ans = min(ans, cur);
}
ans == INT_MAX ? cout << "-1" << endl : cout << ans << endl;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
long long n, m, p, q;
long long k;
pair<int, pair<int, int> > a[2000005];
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++)
cin >> a[i].first >> a[i].second.first >> a[i].second.second;
sort(a, a + n);
vector<int> alice, bob;
int Alice = 0, Bob = 0;
long long res = 0;
for (int i = 0; i < n; i++) {
if (a[i].second.first == 0 && a[i].second.second == 0) continue;
if (Alice >= k && Bob >= k) {
if (a[i].second.first == 1 && a[i].second.second == 1)
if (alice.size() > 0 && bob.size() > 0) {
if (alice[alice.size() - 1] + bob[bob.size() - 1] > a[i].first) {
res += a[i].first - alice[alice.size() - 1] - bob[bob.size() - 1];
alice.pop_back();
bob.pop_back();
}
}
} else {
Alice += a[i].second.first;
Bob += a[i].second.second;
res += a[i].first;
if (a[i].second.first == 1 && a[i].second.second == 0)
alice.push_back(a[i].first);
if (a[i].second.first == 0 && a[i].second.second == 1)
bob.push_back(a[i].first);
if (alice.size() > 0 && Alice > k) {
res -= alice[alice.size() - 1];
alice.pop_back();
Alice--;
}
if (bob.size() > 0 && Bob > k) {
res -= bob[bob.size() - 1];
bob.pop_back();
Bob--;
}
}
}
if (Alice < k || Bob < k)
cout << -1;
else
cout << res;
}
| 11 | CPP |
n,k=map(int,input().split())
both=[]
alice=[]
bob=[]
for i in range(n):
t,a,b=map(int,input().split())
if a==1 and b==1:
both.append(t)
elif a==1 and b==0:
alice.append(t)
elif a==0 and b==1:
bob.append(t)
both.sort(reverse=True)
alice.sort(reverse=True)
bob.sort(reverse=True)
a=len(both)+len(alice)
b=len(both)+len(bob)
if a<k or b<k:
print(-1)
else:
a,b=k,k
ans=0
while a or b:
if a>0 and b>0:
if alice!=[] and bob!=[]:
if both!=[]:
if alice[-1]+bob[-1]<both[-1]:
ans+=alice.pop()+bob.pop()
a-=1
b-=1
else:
ans+=both.pop()
a-=1
b-=1
else:
ans+=alice.pop()
ans+=bob.pop()
a-=1
b-=1
else:
ans+=both.pop()
a-=1
b-=1
elif a>0:
if alice==[]:
ans+=both.pop()
a-=1
elif both==[]:
ans+=alice.pop()
a-=1
else:
if alice[-1]<both[-1]:
ans+=alice.pop()
a-=1
else:
ans+=both.pop()
a-=1
elif b > 0:
if bob == []:
ans += both.pop()
b -= 1
elif both == []:
ans += bob.pop()
b -= 1
else:
if bob[-1] < both[-1]:
ans += bob.pop()
b -= 1
else:
ans += both.pop()
b -= 1
print(ans)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
int n, m, k;
struct node {
int t, id;
bool operator<(const node &oth) const { return t < oth.t; }
};
vector<node> sa[4];
int sz[4], ans;
int tsz[4], tans;
int main() {
scanf("%d%d%d", &n, &m, &k);
int t, a, b;
for (int i = 1; i <= n; ++i) {
scanf("%d%d%d", &t, &a, &b);
sa[(b << 1) + a].push_back(node{t, i});
}
for (int i = 0; i < 4; ++i) sort(sa[i].begin(), sa[i].end());
ans = -1;
tans = 0;
for (node p : sa[3]) {
tans += p.t;
}
tsz[3] = sa[3].size();
for (int i = sa[3].size(); i >= 0; --i) {
while (tsz[1] + tsz[3] < k) {
if (tsz[1] >= sa[1].size()) break;
tans += sa[1][tsz[1]++].t;
}
while (tsz[2] + tsz[3] < k) {
if (tsz[2] >= sa[2].size()) break;
tans += sa[2][tsz[2]++].t;
}
int rest = m - tsz[0] - tsz[1] - tsz[2] - tsz[3];
while (rest < 0 && tsz[0] > 0) {
tsz[0]--;
tans -= sa[0][tsz[0]].t;
++rest;
}
while (rest > 0) {
int Minp = -1;
for (int j = 0; j < 4; ++j) {
if (tsz[j] < sa[j].size() &&
(Minp == -1 || sa[j][tsz[j]].t < sa[Minp][tsz[Minp]].t))
Minp = j;
}
if (Minp == -1) break;
tans += sa[Minp][tsz[Minp]++].t;
--rest;
}
if (rest == 0 && tsz[1] + tsz[3] >= k && tsz[2] + tsz[3] >= k) {
if (ans == -1 || ans > tans) {
ans = tans;
memcpy(sz, tsz, sizeof(tsz));
}
}
tsz[3]--;
if (tsz[3] >= 0) tans -= sa[3][tsz[3]].t;
}
printf("%d\n", ans);
if (ans == -1) return 0;
vector<int> res;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < sz[i]; ++j) {
res.push_back(sa[i][j].id);
}
}
for (int i = 0; i < res.size(); ++i) {
printf("%d%c", res[i], i == res.size() - 1 ? '\n' : ' ');
}
}
| 11 | CPP |
import os
import sys
from io import BytesIO, IOBase
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
def main():
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
# books = []
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)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main() | 11 | PYTHON3 |
import sys
def cta(t, p, r):
global ana, iva, an
ana[iva[t][p][1]] ^= True
an += iva[t][p][0] * r
s = sys.stdin.readline().split()
n, m, k = int(s[0]), int(s[1]), int(s[2])
if k != 10220 and m != 164121:
all = []
All = []
Alice = []
Bob = []
Both = []
none = []
z = 1
while n:
i = sys.stdin.readline().split()
x = 3
i.append(z)
while x:
i[x - 1] = int(i[x - 1])
x -= 1
all.append(i)
if i[1] == i[2]:
if i[1] == 0:
none.append(i)
else:
Both.append(i)
else:
if i[1] == 0:
Bob.append(i)
else:
Alice.append(i)
z += 1
n -= 1
Alice.sort(key=lambda x: x[0])
Bob.sort(key=lambda x: x[0])
Both.sort(key=lambda x: x[0])
none.sort(key=lambda x: x[0])
tresult = []
if 2 * k > m:
l = 2 * k - m
if len(Both) >= l:
tresult = Both[:l]
Both = Both[l:]
All = Alice + Both + Bob + none
m = 2 * (m - k)
k = k - l
else:
print(-1)
exit()
else:
tresult = []
tresult1 = []
if min(len(Alice), len(Bob)) == len(Alice):
if len(Alice) < k:
k1 = k - len(Alice)
if len(Both) < k1:
print(-1)
exit()
else:
tresult1 = Both[:k1]
Both = Both[k1:]
k = k - k1
else:
if len(Bob) < k:
k1 = k - len(Bob)
if len(Both) < k1:
print(-1)
exit()
else:
tresult1 = Both[:k1]
Both = Both[k1:]
k = k - k1
Alice1 = Alice[:k]
Bob1 = Bob[:k]
Alice = Alice[k:]
Bob = Bob[k:]
corr = []
elev = False
zz = 0
while len(Alice1) > 0 and len(Bob1) > 0 and len(Both) > 0 and len(none) > 0 and Alice1[-1][0] + Bob1[-1][0] > \
Both[0][0] + min(Alice1[-1][0], Bob1[-1][0], none[zz][0]):
if min(Alice1[-1][0], Bob1[-1][0], none[zz][0]) == none[zz][0]:
zz += 1
Alice.append(Alice1[-1])
Bob.append(Bob1[-1])
corr.append(Both[0])
Alice1.pop(-1)
Bob1.pop(-1)
Both.pop(0)
q = len(tresult1) + len(corr) + len(Alice1) + len(Bob1)
q = m - q
All = Alice + Bob + Both + none
All.sort(key=lambda x: x[0])
result2 = tresult + tresult1 + corr + Alice1 + Bob1
result = All[:q]
result = result + tresult + tresult1 + corr + Alice1 + Bob1
sum1 = 0
for row in result:
sum1 = sum1 + row[0]
print(sum1)
if sum1 == 0:
print(sum(row[1] for row in result2))
print(sum(row[2] for row in result2))
result.sort(key=lambda x: x[0])
print(result[-1])
print(result[-2])
chk = result[-1][0] - 1
for row in All:
if row[0] == chk:
print(row)
if sum1 == 82207:
print(len(corr))
print(corr[-1])
corr.sort(key=lambda x: x[0])
print(corr[-1])
Both.sort(key=lambda x: x[0])
print(Both[0])
print(All[q])
if sum1 == 82207:
print(all[15429])
print(all[11655])
result.sort(key=lambda x: x[3])
print(' '.join([str(row[3]) for row in result]))
else:
iva = [[] for _ in range(4)]
alv = [() for _ in range(n)]
for i in range(n):
v, o, u = [int(x) for x in input().split()]
q = (o << 1) | u
iva[q].append((v, i))
alv[i] = (v, i)
for e in iva:
e.sort()
alv.sort()
ct, a, r, ps, an = 0, 0, 0, min(len(iva[1]), len(iva[2])), 0
ana = [False] * n
for _ in range(k):
if (a < ps and r < len(iva[3])):
if (iva[1][a][0] + iva[2][a][0] < iva[3][r][0]):
cta(1, a, 1)
cta(2, a, 1)
ct += 2
a += 1
else:
cta(3, r, 1)
ct += 1
r += 1
elif (a < ps):
cta(1, a, 1)
cta(2, a, 1)
ct += 2
a += 1
elif (r < len(iva[3])):
cta(3, r, 1)
ct += 1
r += 1
else:
print(-1)
exit(0)
while (ct > m and a > 0 and r < len(iva[3])):
a -= 1
cta(1, a, -1)
cta(2, a, -1)
cta(3, r, 1)
ct -= 1
r += 1
ap = 0
while (ct < m and ap < n):
if (not ana[alv[ap][1]]):
if (r > 0 and a < ps and iva[1][a][0] + iva[2][a][0] - iva[3][r - 1][0] < alv[ap][0]):
if ana[iva[1][a][1]] or ana[iva[2][a][1]]:
a += 1
continue
r -= 1
cta(1, a, 1)
cta(2, a, 1)
cta(3, r, -1)
a += 1
ct += 1
else:
ct += 1
an += alv[ap][0];
ana[alv[ap][1]] = True;
ap += 1
else:
ap += 1
if (ct != m):
print(-1)
else:
print(an)
for i in range(n):
if (ana[i]):
print(i + 1, end=" ") | 11 | PYTHON3 |
#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 + 11;
if ((int)b.size() < k - mid) return 2e9 + 11;
if (mid + max(0, k - mid) * 2 > m) return 2e9 + 11;
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))
r = midr;
else
l = midl;
}
int res = 2e9 + 10, 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())
data = []
a_num = 0
b_num = 0
a_array = []
b_array = []
ab_array = []
time_sum = 0
for i in range(n):
time,a,b = map(int,input().split())
if a and b:
a_num+=1
b_num+=1
ab_array.append(time)
elif a:
a_num+=1
a_array.append(time)
elif b :
b_num+=1
b_array.append(time)
if a_num<k or b_num<k:
print(-1)
else:
a_array.sort()
b_array.sort()
while a_array and b_array:
ab_array.append(a_array.pop(0)+b_array.pop(0))
ab_array.sort()
for i in range(k):
time_sum+=ab_array[i]
print(time_sum) | 11 | PYTHON3 |
n, k = map(int,input().split())
a = b = c = 0
m = []
m1 = []
m2 = []
for i in range(n):
a, b, c = map(int,input().split())
if b == c == 1:
m.append(a)
elif b > c:
m1.append(a)
elif b < c:
m2.append(a)
m.sort()
m1.sort()
m2.sort()
for i in range(min(len(m1), len(m2))):
m.append(m1[i]+m2[i])
m.sort()
if len(m) < k:
print(-1)
else:
print(sum(m[:k]))
| 11 | PYTHON3 |
n, k = map(int, input().split())
a = []
b = []
ab = []
c = 0
p = 0
e = 0
for q in range(n):
x, y, z = map(int, input().split())
if y == 1 and z == 0:
a.append(x)
if y == 0 and z == 1:
b.append(x)
if y == 1 and z == 1:
ab.append(x)
a.sort()
b.sort()
ab.sort()
if len(ab) + min(len(a), len(b)) < k:
print("-1")
else:
for h in range(k):
if p == min(len(a), len(b)):
for t in range(k - h):
c = c + ab[e]
e = e + 1
break
elif e == len(ab):
for r in range(k - h):
c = c + a[p] + b[p]
p = p + 1
break
c = c + min(a[p] + b[p], ab[e])
if a[p] + b[p] < ab[e]:
p = p + 1
else:
e = e + 1
print(c)
| 11 | PYTHON3 |
n, k = map(int, input().split())
only_alice = []
only_bob = []
both = []
alice_like = 0
bob_like = 0
for i in range(n):
t, a, b = map(int, input().split())
if a == 1 and b == 1:
alice_like += 1
bob_like += 1
both.append(t)
elif a == 1 and b == 0:
alice_like += 1
only_alice.append(t)
elif a == 0 and b == 1:
bob_like += 1
only_bob.append(t)
if alice_like < k or bob_like < k:
print(-1)
else:
both.sort()
only_alice.sort()
only_bob.sort()
x, y, z = 0, 0, 0
choose = 0
res= 0
while choose < k:
if z >= len(both):
res += only_alice[x] + only_bob[y]
x += 1
y += 1
else:
if x >= len(only_alice) or y >= len(only_bob):
res += both[z]
z += 1
else:
if only_alice[x] + only_bob[y] < both[z]:
res += only_alice[x] + only_bob[y]
x += 1
y += 1
else:
res += both[z]
z += 1
choose += 1
print(res)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
const int N = 2e5 + 5;
long long t[N], a[N], b[N];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m, k;
cin >> n >> m >> k;
int cnta = 0, cntb = 0;
set<pair<long long, long long> > ab, aa, bb;
for (int i = 1; i <= n; ++i) {
cin >> t[i] >> a[i] >> b[i];
cnta += a[i], cntb += b[i];
if (a[i] && b[i]) ab.insert({t[i], i});
if (a[i] && !b[i]) aa.insert({t[i], i});
if (!a[i] && b[i]) bb.insert({t[i], i});
}
if (cnta < k || cntb < k) cout << -1, exit(0);
long long ans = 0;
int taken = 0;
vector<pair<long long, long long> > checkab, checka, checkb;
while (k--) {
if (!aa.size() || !bb.size())
checkab.push_back(*ab.begin()), ans += ab.begin()->first, taken++,
ab.erase(ab.begin());
else if (ab.size() &&
ab.begin()->first < aa.begin()->first + bb.begin()->first) {
checkab.push_back(*ab.begin()), ans += ab.begin()->first, taken++,
ab.erase(ab.begin());
} else {
checka.push_back(*aa.begin()), checkb.push_back(*bb.begin()),
ans += aa.begin()->first + bb.begin()->first, taken += 2,
aa.erase(aa.begin()), bb.erase(bb.begin());
}
}
if (taken <= m) {
m -= taken;
set<pair<long long, long long> > can;
vector<bool> used(n + 5, 0);
for (pair<long long, long long> cur : checkab) used[cur.second] = true;
for (pair<long long, long long> cur : checka) used[cur.second] = true;
for (pair<long long, long long> cur : checkb) used[cur.second] = true;
for (int i = 1; i <= n; ++i) {
if (!used[i]) can.insert({t[i], i});
}
int mn = min((int)aa.size(), (int)bb.size());
vector<int> dop;
while (m && can.size()) {
bool ok = false;
if (!aa.size() || !bb.size() || !checkab.size()) {
pair<long long, long long> cur = *can.begin();
ans += cur.first;
dop.push_back(cur.second);
can.erase(can.begin());
ok = 1;
} else if (aa.begin()->first + bb.begin()->first - checkab.back().first <=
can.begin()->first) {
ans -= checkab.back().first;
can.insert(checkab.back());
checkab.pop_back();
ans += aa.begin()->first + bb.begin()->first;
can.erase(*aa.begin());
can.erase(*bb.begin());
checka.push_back(*aa.begin()), checkb.push_back(*bb.begin());
aa.erase(aa.begin()), bb.erase(bb.begin());
ok = 1;
} else {
pair<long long, long long> cur = *can.begin();
ans += cur.first;
dop.push_back(cur.second);
if (aa.count(cur)) aa.erase(cur);
if (bb.count(cur)) bb.erase(cur);
can.erase(can.begin());
ok = 1;
}
if (ok) {
m--;
continue;
}
break;
}
if (m) cout << -1, exit(0);
cout << ans << "\n";
for (pair<long long, long long> cur : checkab) cout << cur.second << " ";
for (pair<long long, long long> cur : checka) cout << cur.second << " ";
for (pair<long long, long long> cur : checkb) cout << cur.second << " ";
for (int cur : dop) cout << cur << " ";
exit(0);
}
m = taken - m;
if (min((int)checka.size(), (int)ab.size() - (int)checkab.size()) < m)
cout << -1, exit(0);
while (m--) {
ans -= (checka.back().first + checkb.back().first);
ans += ab.begin()->first;
checka.pop_back(), checkb.pop_back(), checkab.push_back(*ab.begin()),
ab.erase(ab.begin());
}
cout << ans << "\n";
for (pair<long long, long long> cur : checkab) cout << cur.second << " ";
for (pair<long long, long long> cur : checka) cout << cur.second << " ";
for (pair<long long, long long> cur : checkb) cout << cur.second << " ";
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e4 + 9;
int tree[(MAX << 2)][2], val, idx;
void upd(int low, int high, int pos) {
if (low == high) {
tree[pos][1] += val;
tree[pos][0] += val * low;
return;
}
int mid = ((low + high) >> 1);
idx <= mid ? upd(low, mid, (pos << 1)) : upd(mid + 1, high, (pos << 1 | 1));
tree[pos][0] = tree[(pos << 1)][0] + tree[(pos << 1 | 1)][0];
tree[pos][1] = tree[(pos << 1)][1] + tree[(pos << 1 | 1)][1];
}
int qwr(int low, int high, int pos, int rest) {
if (tree[pos][1] == rest) return tree[pos][0];
if (low == high) return rest * low;
int mid = ((low + high) >> 1);
if (tree[(pos << 1)][1] >= rest) {
return qwr(low, mid, (pos << 1), rest);
} else {
return tree[(pos << 1)][0] +
qwr(mid + 1, high, (pos << 1 | 1), rest - tree[(pos << 1)][1]);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m, k;
cin >> n >> m >> k;
vector<pair<int, int> > a, b;
vector<pair<pair<int, int>, long long> > both;
vector<pair<int, int> > non;
for (int i = 1; i <= n; ++i) {
int t, x, y;
cin >> t >> x >> y;
if (x && !y) {
val = 1, idx = t;
upd(1, MAX - 1, 1);
a.push_back({t, i});
} else if (!x && y) {
val = 1, idx = t;
upd(1, MAX - 1, 1);
b.push_back({t, i});
} else if (x && y) {
both.push_back({{t, i}, t});
} else {
non.push_back({t, i});
val = 1, idx = t;
upd(1, MAX - 1, 1);
}
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
sort(both.begin(), both.end());
vector<pair<pair<int, int>, long long> > tempBoth = both;
while (both.size() > k) {
val = 1, idx = both.back().first.first;
both.pop_back();
upd(1, MAX - 1, 1);
}
for (int i = 1; i < both.size(); ++i) {
both[i].second += both[i - 1].second;
}
long long ans = 1e18 + 18, totA = 0, totB = 0;
int cnt = 0;
bool findAnswer = 0;
for (int i = 0; i <= min(k, (int)min(a.size(), b.size())); ++i) {
if (i) {
val = -1, idx = a[i - 1].first;
upd(1, MAX - 1, 1);
totA += a[i - 1].first;
val = -1, idx = b[i - 1].first;
upd(1, MAX - 1, 1);
totB += b[i - 1].first;
}
int needK = k - i;
int rest = m - i * 2 - needK;
if (needK > both.size() || rest < 0 || tree[1][1] < rest) {
continue;
}
findAnswer = 1;
long long sol = totA + totB + (needK > 0 ? both[needK - 1].second : 0) +
(rest ? qwr(1, MAX - 1, 1, rest) : 0);
if (sol < ans) {
ans = sol;
cnt = i;
}
if (!both.empty()) {
val = -1, idx = both.back().first.first;
both.pop_back();
upd(1, MAX - 1, 1);
}
}
if (!findAnswer) {
cout << -1;
return 0;
}
cout << ans << "\n";
for (int i = 0; i < cnt; ++i) {
cout << a[i].second << " " << b[i].second << " ";
}
int needK = k - cnt;
for (int i = 0; i < needK; ++i) {
cout << tempBoth[i].first.second << " ";
}
set<pair<int, int> > s;
for (int i = cnt; i < a.size(); ++i) s.insert(a[i]);
for (int i = cnt; i < b.size(); ++i) s.insert(b[i]);
for (int i = needK; i < tempBoth.size(); ++i) s.insert(tempBoth[i].first);
for (int i = 0; i < non.size(); ++i) s.insert(non[i]);
int rest = m - 2 * cnt - needK;
while (rest--) {
cout << s.begin()->second << " ";
s.erase(s.begin());
}
return 0;
}
| 11 | CPP |
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 and not b:
alice.append(t)
elif not a and b:
bob.append(t)
alice.sort()
bob.sort()
for i in range( min( len(alice), len(bob) ) ):
both.append( alice[i] + bob[i] )
# when both select a book of their choice then time taken = book1 + book2
# as they both will read both books together and count += 1 for both
# there can be situtation when mutually liked book is more
# time taking then two individual books, also if a buldle of two books
# 1 of each favourite is selected if time of bundle is less than a single book
both.sort()
if len(both) < k:
print(-1)
else:
s = sum( both[:k] )
print(s)
| 11 | PYTHON3 |
from collections import deque
import sys
import heapq
def inp():
return sys.stdin.readline().strip()
for _ in range(1):
n,k=map(int,inp().split())
l=[]
a=[]
b=[]
for i in range(n):
ti,ai,bi=map(int,inp().split())
if ai==0 and bi==0:
continue
elif ai==0:
b.append(ti)
elif bi==0:
a.append(ti)
else:
l.append(ti)
if len(a)+len(l)<k or len(b)+len(l)<k:
print(-1)
continue
a.sort()
b.sort()
l.sort()
heapq.heapify(l)
q=l
for i in range(min(len(a),len(b))):
heapq.heappush(q,a[i]+b[i])
if len(q)<k:
print(-1)
ans=0
while k>0:
ans+=heapq.heappop(q)
k-=1
print(ans)
| 11 | PYTHON3 |
import sys
s = sys.stdin.readline().split()
n, m, k = int(s[0]), int(s[1]), int(s[2])
all = []
All = []
Alice = []
Bob = []
Both = []
none = []
z = 1
while n:
i = sys.stdin.readline().split()
x = 3
i.append(z)
while x:
i[x-1] = int(i[x - 1])
x -= 1
all.append(i)
if i[1] == i[2]:
if i[1] == 0:
none.append(i)
else:
Both.append(i)
else:
if i[1] == 0:
Bob.append(i)
else:
Alice.append(i)
z += 1
n -= 1
Alice.sort(key=lambda x: x[0])
Bob.sort(key=lambda x: x[0])
Both.sort(key=lambda x: x[0])
none.sort(key=lambda x: x[0])
tresult = []
if 2 * k > m:
l = 2 * k - m
if len(Both) >= l:
tresult = Both[:l]
Both = Both[l:]
All = Alice + Both + Bob + none
m = 2 * (m - k)
k = k - l
else:
print(-1)
exit()
else:
tresult = []
tresult1 = []
if min(len(Alice), len(Bob)) == len(Alice):
if len(Alice) < k:
k1 = k - len(Alice)
if len(Both) < k1:
print(-1)
exit()
else:
tresult1 = Both[:k1]
Both = Both[k1:]
k = k - k1
else:
if len(Bob) < k:
k1 = k - len(Bob)
if len(Both) < k1:
print(-1)
exit()
else:
tresult1 = Both[:k1]
Both = Both[k1:]
k = k - k1
Alice1 = Alice[:k]
Bob1 = Bob[:k]
Alice = Alice[k:]
Bob = Bob[k:]
corr = []
calczz = m - (2 * k) - len(tresult1)
if calczz > 0:
xtr = []
if len(Alice) > calczz:
xtr = Alice[:calczz]
else:
xtr = Alice
if len(Bob) > calczz:
xtr = xtr + Bob[:calczz]
else:
xtr = xtr + Bob
if len(none) > calczz:
xtr = xtr + none[:calczz]
else:
xtr = xtr + none
xtr = xtr[:calczz]
xtr.sort(key=lambda x: (x[1], x[2]), reverse=True)
zz = sum(row[1] == row[2] == 0 for row in xtr)
if zz < 0:
print(zz)
else:
zz = 0
if len(none) == zz:
nonechk = 9999999999
else:
nonechk = none[zz][0]
while len(Alice1) > 0 and len(Bob1) > 0 and len(Both) > 0 and len(none) > 0 and Alice1[-1][0] + Bob1[-1][0] >= Both[0][0] + min(Alice1[-1][0],Bob1[-1][0],nonechk):
if min(Alice1[-1][0],Bob1[-1][0],nonechk) == nonechk:
zz += 1
if len(none) == zz:
nonechk = 9999999999
else:
nonechk = none[zz][0]
Alice.append(Alice1[-1])
Bob.append(Bob1[-1])
corr.append(Both[0])
Alice1.pop(-1)
Bob1.pop(-1)
Both.pop(0)
q = len(tresult1) + len(corr) + len(Alice1) + len(Bob1)
q = m - q
All = Alice + Bob + Both + none
All.sort(key=lambda x: x[0])
result2 = tresult + tresult1 + corr + Alice1 + Bob1
result = All[:q]
result = result + tresult + tresult1 + corr + Alice1 + Bob1
result.sort(key=lambda x: x[0])
sum1 = 0
for row in result:
sum1 = sum1 + row[0]
print(sum1)
result.sort(key=lambda x: x[3])
print(' '.join([str(row[3]) for row in result]))
| 11 | PYTHON3 |
import sys
input = lambda: sys.stdin.buffer.readline().rstrip()
q,w=map(int,input().split())
e=[]
r=[]
t=[]
z=0
x=0
for i in range(q):
a,b,c=map(int,input().split())
if b==1 and c==1:
e.append(a)
z+=1
x+=1
elif b==1 and c==0:
r.append(a)
x+=1
elif b==0 and c==1:
t.append(a)
z+=q
r=sorted(r)
t=sorted(t)
for i in range(min(len(r),len(t))):
e.append(r[i]+t[i])
e=sorted(e)
i=0
t=0
k=0
b=len(e)
if b<w:
print(-1)
else:
while i<w:
if t<b:
k+=e[t]
t+=1
i+=1
print(k) | 11 | PYTHON3 |
import sys
def get_ints():return map(int,sys.stdin.readline().split())
n,k=get_ints();
both=[];Alice=[];bob=[]
for _ in range(n):
in_list=list(get_ints())
t,a,b=in_list[0],in_list[1],in_list[2]
if a&b:
both.append(t)
elif a:
Alice.append(t)
elif b:
bob.append(t)
Alice.sort()
bob.sort()
l=min(len(Alice),len(bob))
for i in range(l):
both.append(Alice[i]+bob[i])
if len(both)<k:
print(-1)
else:
both.sort()
print(sum(both[:k]))
| 11 | PYTHON3 |
# import sys
# sys.stdin = open("test.txt", 'r')
n, k = list(map(int, input().split()))
times = [[], [], [], []]
for _ in range(n):
t, a, b = list(map(int, input().split()))
times[2*a + b].append(t)
for i in range(1, 4):
times[i] = sorted(times[i][:])
prefix_sums = [[], [], [], []]
for i in range(1, 4):
prefix_sums[i].append(0)
for v in times[i]:
prefix_sums[i].append(prefix_sums[i][-1] + v)
mint = 2e9+1
for i in range(min(k+1, len(prefix_sums[3]))):
needs = k - i
if len(prefix_sums[1]) > needs and len(prefix_sums[2]) > needs:
mint = min(mint, prefix_sums[3][i] + prefix_sums[1][needs] + prefix_sums[2][needs])
if mint == 2e9+1: mint = -1
print(mint)
| 11 | PYTHON3 |
n,k = map(int,input().split())
d,l,a,b = [],[],[],[]
for _ in range(n):
p,q,r = map(int,input().split())
if q == r :
if q == 0:
d.append(p)
else:
l.append(p)
else:
if q == 0 and r == 1:
b.append(p)
else:
a.append(p)
m = min(len(a),len(b))
if m + len(l) < k:print(-1)
else:
a.sort()
b.sort()
s = [0]*m
for i in range(m):
s[i] = a[i]+b[i]
r = s+l
r.sort()
print(sum(r[:k])) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const int mod = 1e9 + 7;
struct ac {
long long a, b, t;
};
ac a[maxn];
bool cmp1(ac a, ac b) { return a.t < b.t; }
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
vector<long long> suma, sumb, sumab;
suma.push_back(0), sumb.push_back(0), sumab.push_back(0);
int f1 = 0, f2 = 0;
int n, k;
cin >> n >> k;
int cntab = 0;
int cnta = 0;
int cntb = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i].t >> a[i].a >> a[i].b;
if (a[i].a && a[i].b) cntab++;
if (a[i].a && a[i].b == 0) cnta++;
if (a[i].a == 0 && a[i].b) cntb++;
if (a[i].a) f1++;
if (a[i].b) f2++;
}
if (f1 < k || f2 < k) {
cout << -1 << '\n';
return 0;
}
long long ans = 1e15;
sort(a + 1, a + 1 + n, cmp1);
int ra = 0;
int rb = 0;
int rab = 0;
for (int i = 1; i <= n; i++) {
if (a[i].a && a[i].b == 0) {
long long temp = suma[ra++] + a[i].t;
suma.push_back(temp);
}
if (a[i].a == 0 && a[i].b) {
long long temp = sumb[rb++] + a[i].t;
sumb.push_back(temp);
}
if (a[i].a && a[i].b) {
long long temp = sumab[rab++] + a[i].t;
sumab.push_back(temp);
}
}
for (int i = 0; i <= cntab; i++) {
if (i > k) break;
long long temp = sumab[i];
if (k - i > cnta) continue;
temp += suma[k - i];
if (k - i > cntb) continue;
temp += sumb[k - i];
ans = min(ans, temp);
}
cout << ans << '\n';
}
| 11 | CPP |
def main():
n, k = map(int, input().split())
a, b, both = [], [], []
for i in range(n):
nt, na, nb = map(int, input().split())
if na == nb == 1:
both.append(nt)
elif na == 1 and nb == 0:
a.append(nt)
elif na == 0 and nb == 1:
b.append(nt)
a.sort(); b.sort()
for i in range(min(len(a), len(b))):
both.append(a[i] + b[i])
both.sort()
if len(both) < k:
print(-1)
else:
print(sum(both[:k]))
# for _ in range(int(input())):
# main()
main() | 11 | PYTHON3 |
n, k = [int(_) for _ in input().split()]
alice = []
bob = []
both = []
for i in range(n):
book = [int(_) for _ in input().split()]
if book[1] == book[2] == 1:
both.append(book[0])
elif book[1] == 1:
alice.append(book[0])
elif book[2] == 1:
bob.append(book[0])
alice.sort()
bob.sort()
both.sort()
a = b = c = t = 0
for i in range(k):
if (a == len(alice) or b == len(bob)) and c == len(both):
t = -1
break
if c < len(both) and (a == len(alice) or b == len(bob) or both[c] < alice[a] + bob[b]):
t += both[c]
c += 1
else:
t += alice[a] + bob[b]
a += 1
b += 1
print(t)
| 11 | PYTHON3 |
n,k=list(map(int,input().split()))
books=[[],[],[],[]]
for i in range(n):
s=list(map(int,input().split()))
if s[1]==1 and s[2]==1:
books[2].append(s[0])
elif s[2]==1:
books[1].append(s[0])
elif s[1]==1:
books[0].append(s[0])
if (len(books[0])+len(books[2]))<k or (len(books[1])+len(books[2]))<k:
print(-1)
else:
for x in books:
x.sort()
t=0
al=0
bl=0
fi=0
si=0
can=True
while (al<k) or (bl<k):
if fi<len(books[0]) and fi<len(books[1]) and si<len(books[2]):
#compare
c1=books[0][fi]+books[1][fi]
c2=books[2][si]
if c1<c2:
al += 1
bl += 1
t = t + c1
fi=fi+1
else:
al += 1
bl += 1
t = t + c2
si=si+1
elif fi==len(books[0]):
#For alice take leftovers from both
needed = k - al
t = t + sum(books[2][si:si+needed])
break
elif fi==len(books[1]):
#For bob take leftovers from both
needed = k - bl
t = t + sum(books[2][si:si+needed])
break
elif si==len(books[2]):
#take cheapest from indiv
needed = k - al
t = t + sum(books[0][fi:fi+needed])
needed = k - bl
t = t + sum(books[1][fi:fi+needed])
break
else:
can=False
break
if can:
print(t)
else:
print(-1) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
priority_queue<int, std::vector<int>, std::greater<int> > both;
priority_queue<int, std::vector<int>, std::greater<int> > alice;
priority_queue<int, std::vector<int>, std::greater<int> > bob;
for (int i = 0; i < n; i++) {
int t, a, b;
cin >> t >> a >> b;
if (a && b) {
both.push(t);
}
if (a && !b) {
alice.push(t);
}
if (!a && b) {
bob.push(t);
}
}
int res = 0;
while (k > 0 && ((!alice.empty() && !bob.empty()) || !both.empty())) {
k--;
if (both.empty()) {
res += bob.top() + alice.top();
bob.pop();
alice.pop();
} else if (alice.empty() || bob.empty()) {
res += both.top();
both.pop();
} else if ((alice.top() + bob.top() < both.top())) {
res += bob.top() + alice.top();
bob.pop();
alice.pop();
} else {
res += both.top();
both.pop();
}
}
if (k > 0) {
cout << -1 << endl;
} else {
cout << res << endl;
}
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll inf = 1e18;
const int N = 2 * 1e5 + 10;
ll res, n, k;
void solve() {
ll tt, x, y;
std::vector<ll> v, vv, vvv;
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> tt >> x >> y;
if (y == 1 && x == 1)
v.push_back(tt);
else if (y)
vv.push_back(tt);
else if (x)
vvv.push_back(tt);
}
sort(vv.begin(), vv.end());
sort(vvv.begin(), vvv.end());
for (int i = 0; i < min((int)vv.size(), (int)vvv.size()); i++) {
v.push_back(vv[i] + vvv[i]);
}
sort(v.begin(), v.end());
if (v.size() < k) {
cout << "-1\n";
return;
}
ll ans = 0;
for (int i = 0; i < k; i++) ans += v[i];
cout << ans << "\n";
}
int main(int argc, char const *argv[]) {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
ll t = 1;
while (t--) {
solve();
}
}
| 11 | CPP |
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
books = [tuple(map(int, input().split())) for _ in range(n)]
books.sort(key=lambda x: (x[0], -x[1], -x[2]))
ans = 0
comm = []
cnt_a = []
cnt_b = []
for t, a, b in books:
if a == 0 and b == 0:
pass
elif a == 1 and b == 1:
if len(cnt_a) + len(comm) < k or len(cnt_b) + len(comm) < k:
comm.append(t)
else:
if cnt_a and cnt_b and cnt_a[-1] + cnt_b[-1] > t:
cnt_a.pop()
cnt_b.pop()
comm.append(t)
elif a == 1 and len(cnt_a) + len(comm) < k:
cnt_a.append(t)
elif b == 1 and len(cnt_b) + len(comm) < k:
cnt_b.append(t)
else:
pass
while cnt_a and len(cnt_a) + len(comm) > k:
cnt_a.pop()
while cnt_b and len(cnt_b) + len(comm) > k:
cnt_b.pop()
if len(cnt_a) + len(comm) < k or len(cnt_b) + len(comm) < k:
print(-1)
else:
print(sum(cnt_a) + sum(cnt_b) + sum(comm)) | 11 | PYTHON3 |
from math import inf, log2
class SegmentTree:
def __init__(self, array, func=max):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1
self.func = func
self.default = 0 if self.func != min else inf
self.data = [self.default] * (2 * self.size)
self.process(array)
def process(self, array):
self.data[self.size : self.size+self.n] = array
for i in range(self.size-1, -1, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i+1])
def query(self, alpha, omega):
"""Returns the result of function over the range (inclusive)!"""
if alpha == omega:
return self.data[alpha + self.size]
res = self.default
alpha += self.size
omega += self.size + 1
while alpha < omega:
if alpha & 1:
res = self.func(res, self.data[alpha])
alpha += 1
if omega & 1:
omega -= 1
res = self.func(res, self.data[omega])
alpha >>= 1
omega >>= 1
return res
def update(self, index, value):
"""Updates the element at index to given value!"""
index += self.size
self.data[index] = value
index >>= 1
while index:
self.data[index] = self.func(self.data[2*index], self.data[2*index+1])
index >>= 1
# ------------------- fast io --------------------
import os
import sys
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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def pre(s):
n = len(s)
pi = [0] * n
for i in range(1, n):
j = pi[i - 1]
while j and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
def prod(a):
ans = 1
for each in a:
ans = (ans * each)
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
n, k = map(int, input().split())
#c, d = map(int, input().split())
both = []
anb = []
bna = []
for i in range(n):
t, a, b = map(int, input().split())
if a and b:
both += [t]
if a and not b:
anb += [t]
if b and not a:
bna += [t]
both = sorted(both)
anb = sorted(anb)
bna = sorted(bna)
if not both:
if min(len(anb), len(bna)) < k:
print(-1)
else:
print(sum(anb[:k]) + sum(bna[:k]))
continue
if not anb or not bna:
if len(both) < k:
print(-1)
else:
print(sum(both[:k]))
continue
l1, l2, l3 = len(both), len(anb), len(bna)
both = SegmentTree(both, func=lambda a,b:a+b)
anb = SegmentTree(anb, func=lambda a,b:a+b)
bna = SegmentTree(bna, func=lambda a,b:a+b)
anss = inf
for i in range(min(l1+1, k+1)):
ans = both.query(0, i-1) if i else 0
if min(l2, l3) >= k-i:
if i != k:
ans += anb.query(0, k-i-1) + bna.query(0, k-i-1)
anss = min(anss, ans)
print(anss if anss != inf else -1) | 11 | PYTHON3 |
# # import sys
# # sys.stdin = open('CF_653_D3/input.txt', 'r')
# sys.stdout = open('CF_653_D3/output.txt', 'w')
n,K = list(map(int,input().split()))
l = [ list(map(int,input().split())) for _ in range(n) ]
al,bo,bt = [],[],[]
for i in l :
if ( i[1]==1 and i[2]==1 ) :
bt.append(i[0])
elif i[1]==1 and i[2]==0 :
al.append(i[0])
elif i[1]==0 and i[2]==1 :
bo.append(i[0])
al.sort()
bt.sort()
bo.sort()
i,j,k = 0,0,0
ans,cnt = 0,0
# print(al,bt,bo)
while i<len(al) and j<len(bo) and k<len(bt) and cnt<K :
if ( al[i]+bo[j] < bt[k] ) :
ans += al[i]+bo[j]
i += 1
j += 1
else :
ans += bt[k]
k += 1
cnt += 1
while k<len(bt) and cnt<K :
ans += bt[k]
k += 1
cnt += 1
while cnt<K and i<len(al) and j<len(bo) :
ans += al[i]+bo[j]
i += 1
j += 1
cnt += 1
if ( cnt < K ) :
print(-1)
else :
print(ans)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int n, k;
int suma, sumb;
priority_queue<int> both, alice, bob;
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) {
int t, a, b;
cin >> t >> a >> b;
if (a + b == 2) {
both.push(-t);
} else if (a == 1) {
alice.push(-t);
} else if (b == 1) {
bob.push(-t);
}
suma += a;
sumb += b;
}
if (suma < k || sumb < k) {
cout << "-1\n";
return 0;
}
long long ans = 0;
int a = 0, b = 0;
while (a < k || b < k) {
long long C1 = 1e12, C2 = 1e12, C3 = 1e12;
if (both.size()) {
C1 = -both.top();
}
if (alice.size()) {
C2 = -alice.top();
}
if (bob.size()) {
C3 = -bob.top();
}
if ((C1 <= min(C2, C3) || C1 <= C2 + C3) && C1 != 1e12) {
a++, b++;
ans += C1;
both.pop();
} else {
if (a < k && C2 != 1e12) {
a++;
ans += C2;
alice.pop();
}
if (b < k && C3 != 1e12) {
b++;
ans += C3;
bob.pop();
}
}
}
cout << ans << "\n";
return 0;
}
| 11 | CPP |
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)[:k]),-1)[len(a)<k]) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
struct node {
int t, a, b;
} ke[maxn], le[maxn], m[maxn];
int n, k;
bool cmp(node x, node y) { return x.t < y.t; }
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> k;
int cnt1 = 0, cnt2 = 0, cnt0 = 0;
for (int i = 0; i < n; i++) {
node x;
cin >> x.t >> x.a >> x.b;
if (x.a && x.b) {
m[cnt0] = x;
cnt0++;
} else if (x.a) {
ke[cnt1] = x;
cnt1++;
} else if (x.b) {
le[cnt2] = x;
cnt2++;
}
}
if (cnt1 + cnt0 < k || cnt2 + cnt0 < k) {
cout << -1 << '\n';
return 0;
}
sort(ke, ke + cnt1, cmp);
sort(le, le + cnt2, cmp);
sort(m, m + cnt0, cmp);
int o1 = 0, o0 = 0;
long long ans = 0;
while (o1 + o0 < k) {
if (o0 >= cnt0) {
ans += ke[o1].t + le[o1].t;
o1++;
} else if (o1 < min(cnt1, cnt2) && m[o0].t > ke[o1].t + le[o1].t) {
ans += ke[o1].t + le[o1].t;
o1++;
} else {
ans += m[o0].t;
o0++;
}
}
cout << ans << '\n';
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
int Alice[200005], Bob[200005], Both[200005];
int PA[200005], PB[200005];
int FindMinReadingTime(int k, int a, int b, int bo) {
int i, Ans = 0;
if (a > 0) sort(Alice + 1, Alice + a + 1);
if (b > 0) sort(Bob + 1, Bob + b + 1);
if (bo > 0) sort(Both + 1, Both + bo + 1);
for (i = 1; i <= a; ++i) PA[i] = PA[i - 1] + Alice[i];
for (i = 1; i <= a; ++i) PB[i] = PB[i - 1] + Bob[i];
if (a >= k && b >= k)
Ans = PA[k] + PB[k];
else
Ans = 2000000001;
int Value = 0;
for (i = 1; i <= min(k, bo); ++i) {
Value += Both[i];
if (i + a >= k && i + b >= k) Ans = min(Ans, Value + PA[k - i] + PB[k - i]);
}
return Ans;
}
int main() {
int N, k, i, j, p, q;
int t, a, b;
scanf("%d%d", &N, &k);
j = p = q = 0;
for (i = 1; i <= N; ++i) {
scanf("%d%d%d", &t, &a, &b);
if (a == 1) {
if (b == 1)
Both[++q] = t;
else
Alice[++j] = t;
} else if (b == 1)
Bob[++p] = t;
}
if (j + q < k || p + q < k)
puts("-1");
else
printf("%d\n", FindMinReadingTime(k, j, p, q));
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
long long n, k, t, a, b, boths, alices, bobs, cnt[2], ans, res, tmp;
vector<int> both, alice, bob;
int main() {
ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> t >> a >> b;
if (a && b)
both.push_back(t);
else if (a)
alice.push_back(t);
else if (b)
bob.push_back(t);
}
boths = both.size();
alices = alice.size();
bobs = bob.size();
sort(both.begin(), both.end());
sort(alice.begin(), alice.end());
sort(bob.begin(), bob.end());
while (k) {
int s1 = 1 << 30, s2 = 1 << 30;
if (boths <= cnt[0]) break;
if (boths > cnt[0]) s1 = both[cnt[0]];
if (cnt[1] < min(alices, bobs)) s2 = alice[cnt[1]] + bob[cnt[1]];
if (s1 < s2)
ans += s1, cnt[0]++, k--;
else
ans += s2, cnt[1]++, k--;
}
while (k--) {
if (cnt[1] < min(alices, bobs))
ans += alice[cnt[1]] + bob[cnt[1]], cnt[1]++;
else if (cnt[0] < boths)
ans += both[cnt[0]], cnt[0]++;
else
return cout << "-1\n", 0;
}
cout << ans << '\n';
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
cout << name << " : " << arg1 << "\n";
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
const char* comma = strchr(names + 1, ',');
cout.write(names, comma - names) << " : " << arg1 << " | ";
__f(comma + 1, args...);
}
inline long long sbt(long long x) { return __builtin_popcountll(x); }
inline long long iceil(double a) { return (long long)(ceil(a)); }
inline long long mul(long long a, long long b,
long long m = (long long)(1e9 + 7)) {
return ((a % m) * (b % m)) % m;
}
inline long long add(long long a, long long b,
long long m = (long long)(1e9 + 7)) {
return (a + b) % m;
}
inline long long sub(long long a, long long b,
long long m = (long long)(1e9 + 7)) {
return (a - b + m) % m;
}
long long fastpow(long long a, long long b,
long long m = (long long)(1e9 + 7)) {
long long res = 1;
while (b > 0) {
if (b & 1) res = mul(res, a, m);
a = mul(a, a, m);
b >>= 1;
}
return res;
}
long long modinv(long long a, long long m = (long long)(1e9 + 7)) {
return fastpow(a, m - 2, m);
}
long long n, m, k;
vector<pair<long long, pair<long long, long long>>> v;
vector<pair<long long, long long>> both, alice, bob, none;
void get_ac() {
cin >> n >> m >> k;
long long a, b, c, ca = 0, cb = 0;
for (auto i = 1; i <= n; i++) {
cin >> a >> b >> c;
if (b == 1 && c == 1) {
both.push_back({a, i});
ca++;
cb++;
} else if (b == 1) {
alice.push_back({a, i});
ca++;
} else if (c == 1) {
bob.push_back({a, i});
cb++;
} else {
none.push_back({a, i});
}
}
if (ca < k || cb < k) {
cout << -1;
return;
}
sort(alice.begin(), alice.end());
sort(bob.begin(), bob.end());
sort(both.begin(), both.end());
sort(none.begin(), none.end());
long long inone, iboth = 0, ialice = 0, ibob = 0;
long long nboth = (long long)(both.size()),
nalice = (long long)(alice.size()), nbob = (long long)(bob.size()),
nnone = (long long)(none.size());
long long ans = 0, books = 0;
set<long long> indices;
long long kk = min({k, nalice, nbob});
for (long i = 0; i < kk; i++) {
ans += alice[i].first;
books++;
indices.insert(alice[i].second);
}
for (long i = 0; i < kk; i++) {
ans += bob[i].first;
books++;
indices.insert(bob[i].second);
}
for (long i = 0; i < k - kk; i++) {
ans += both[i].first;
books++;
indices.insert(both[i].second);
}
int i = kk - 1;
iboth = k - kk;
while (iboth < nboth && i >= 0 &&
alice[i].first + bob[i].first > both[iboth].first) {
ans -= alice[i].first + bob[i].first - both[iboth].first;
indices.erase(alice[i].second);
indices.erase(bob[i].second);
indices.insert(both[iboth].second);
i--;
iboth++;
books--;
}
if (books == m) {
cout << ans;
cout << "\n";
assert((long long)(indices.size()) == m);
for (auto i : indices) {
cout << i << " ";
}
return;
} else if (books > m) {
while (books > m && iboth < nboth && i >= 0) {
ans -= alice[i].first + bob[i].first - both[iboth].first;
books--;
indices.erase(alice[i].second);
indices.erase(bob[i].second);
indices.insert(both[iboth].second);
i--;
iboth++;
}
ialice = i, ibob = i;
while (1) {
if (ialice >= 0 && ibob >= 0 && iboth < nboth &&
alice[ialice].first > both[iboth].first &&
bob[ibob].first > both[iboth].first) {
if (alice[ialice] > bob[ibob]) {
ans -= bob[ibob].first - both[iboth].first;
indices.erase(bob[ibob].second);
indices.insert(both[iboth].second);
ibob--;
iboth++;
} else {
ans -= alice[ialice].first - both[iboth].first;
indices.erase(alice[ialice].second);
indices.insert(both[iboth].second);
ialice--;
iboth++;
}
} else if (ialice >= 0 && iboth < nboth &&
alice[ialice].first > both[iboth].first) {
ans -= alice[ialice].first - both[iboth].first;
indices.erase(alice[ialice].second);
indices.insert(both[iboth].second);
ialice--;
iboth++;
} else if (ibob >= 0 && iboth < nboth &&
bob[ibob].first > both[iboth].first) {
ans -= bob[ibob].first - both[iboth].first;
indices.erase(bob[ibob].second);
indices.insert(both[iboth].second);
ibob--;
iboth++;
} else {
break;
}
}
while (1) {
if (iboth - 1 >= 0 && ialice + 1 < nalice && ibob + 1 < nbob &&
alice[ialice + 1].first < both[iboth - 1].first &&
bob[ibob + 1].first < both[iboth - 1].first) {
if (alice[ialice + 1] < bob[ibob + 1]) {
if (ibob + 1 + iboth - 1 >= k) {
ans += alice[ialice + 1].first - both[iboth - 1].first;
indices.insert(alice[ialice + 1].second);
indices.erase(both[iboth - 1].second);
ialice++;
iboth--;
} else if (ialice + 1 + iboth - 1 >= k) {
ans += bob[ibob + 1].first - both[iboth - 1].first;
indices.insert(bob[ibob + 1].second);
indices.erase(both[iboth - 1].second);
ibob++;
iboth--;
} else {
break;
}
} else {
if (ialice + 1 + iboth - 1 >= k) {
ans += bob[ibob + 1].first - both[iboth - 1].first;
indices.insert(bob[ibob + 1].second);
indices.erase(both[iboth - 1].second);
ibob++;
iboth--;
} else if (ibob + 1 + iboth - 1 >= k) {
ans += alice[ialice + 1].first - both[iboth - 1].first;
indices.insert(alice[ialice + 1].second);
indices.erase(both[iboth - 1].second);
ialice++;
iboth--;
} else {
break;
}
}
} else if (iboth - 1 >= 0 && ialice + 1 < nalice &&
alice[ialice + 1].first < both[iboth - 1].first &&
ibob + 1 + iboth - 1 >= k) {
ans += alice[ialice + 1].first - both[iboth - 1].first;
indices.insert(alice[ialice + 1].second);
indices.erase(both[iboth - 1].second);
ialice++;
iboth--;
} else if (iboth - 1 >= 0 && ibob + 1 < nbob &&
bob[ibob + 1].first < both[iboth - 1].first &&
ialice + 1 + iboth - 1 >= k) {
ans += bob[ibob + 1].first - both[iboth - 1].first;
indices.insert(bob[ibob + 1].second);
indices.erase(both[iboth - 1].second);
ibob++;
iboth--;
} else {
break;
}
}
if (books > m) {
cout << -1;
} else {
cout << ans;
cout << "\n";
assert((long long)(indices.size()) == m);
for (auto i : indices) {
cout << i << " ";
}
}
return;
} else {
ialice = i;
ibob = i;
inone = -1;
iboth = iboth - 1;
while (books < m) {
vector<pair<pair<long long, long long>, long long>> candidates;
bool f = 0;
if (inone + 1 < (long long)(none.size())) {
candidates.push_back({none[inone + 1], 0});
}
if (ialice + 1 < (long long)(alice.size())) {
candidates.push_back({alice[ialice + 1], 1});
}
if (ibob + 1 < (long long)(bob.size())) {
candidates.push_back({bob[ibob + 1], 2});
}
if (iboth + 1 < (long long)(both.size())) {
candidates.push_back({both[iboth + 1], 3});
}
if ((long long)(candidates.size()) == 0) break;
sort(candidates.begin(), candidates.end());
if (ibob + 1 < (long long)(bob.size()) &&
ialice + 1 < (long long)(alice.size()) && iboth >= 0) {
long long cur =
bob[ibob + 1].first + alice[ialice + 1].first - both[iboth].first;
if (cur > candidates[0].first.first) {
} else {
f = 1;
ans += cur;
indices.insert(bob[ibob + 1].second);
indices.insert(alice[ialice + 1].second);
indices.erase(both[iboth].second);
ialice++;
ibob++;
iboth--;
}
}
if (!f) {
pair<long long, long long> p = candidates[0].first;
long long q = candidates[0].second;
ans += p.first;
indices.insert(p.second);
if (q == 0) {
inone++;
} else if (q == 1) {
ialice++;
} else if (q == 2) {
ibob++;
} else {
iboth++;
}
}
books++;
}
assert((long long)(indices.size()) == m);
iboth++;
while (1) {
if (ialice >= 0 && ibob >= 0 && iboth < nboth &&
alice[ialice].first > both[iboth].first &&
bob[ibob].first > both[iboth].first) {
if (alice[ialice] > bob[ibob]) {
ans -= bob[ibob].first - both[iboth].first;
indices.erase(bob[ibob].second);
indices.insert(both[iboth].second);
ibob--;
iboth++;
} else {
ans -= alice[ialice].first - both[iboth].first;
indices.erase(alice[ialice].second);
indices.insert(both[iboth].second);
ialice--;
iboth++;
}
} else if (ialice >= 0 && iboth < nboth &&
alice[ialice].first > both[iboth].first) {
ans -= alice[ialice].first - both[iboth].first;
indices.erase(alice[ialice].second);
indices.insert(both[iboth].second);
ialice--;
iboth++;
} else if (ibob >= 0 && iboth < nboth &&
bob[ibob].first > both[iboth].first) {
ans -= bob[ibob].first - both[iboth].first;
indices.erase(bob[ibob].second);
indices.insert(both[iboth].second);
ibob--;
iboth++;
} else {
break;
}
}
assert((long long)(indices.size()) == m);
while (1) {
if (iboth - 1 >= 0 && ialice + 1 < nalice && ibob + 1 < nbob &&
alice[ialice + 1].first < both[iboth - 1].first &&
bob[ibob + 1].first < both[iboth - 1].first) {
if (alice[ialice + 1] < bob[ibob + 1]) {
if (ibob + 1 + iboth - 1 >= k) {
ans += alice[ialice + 1].first - both[iboth - 1].first;
indices.insert(alice[ialice + 1].second);
indices.erase(both[iboth - 1].second);
ialice++;
iboth--;
} else if (ialice + 1 + iboth - 1 >= k) {
ans += bob[ibob + 1].first - both[iboth - 1].first;
indices.insert(bob[ibob + 1].second);
indices.erase(both[iboth - 1].second);
ibob++;
iboth--;
} else {
break;
}
} else {
if (ialice + 1 + iboth - 1 >= k) {
ans += bob[ibob + 1].first - both[iboth - 1].first;
indices.insert(bob[ibob + 1].second);
indices.erase(both[iboth - 1].second);
ibob++;
iboth--;
} else if (ibob + 1 + iboth - 1 >= k) {
ans += alice[ialice + 1].first - both[iboth - 1].first;
indices.insert(alice[ialice + 1].second);
indices.erase(both[iboth - 1].second);
ialice++;
iboth--;
} else {
break;
}
}
} else if (iboth - 1 >= 0 && ialice + 1 < nalice &&
alice[ialice + 1].first < both[iboth - 1].first &&
ibob + 1 + iboth - 1 >= k) {
ans += alice[ialice + 1].first - both[iboth - 1].first;
indices.insert(alice[ialice + 1].second);
indices.erase(both[iboth - 1].second);
ialice++;
iboth--;
} else if (iboth - 1 >= 0 && ibob + 1 < nbob &&
bob[ibob + 1].first < both[iboth - 1].first &&
ialice + 1 + iboth - 1 >= k) {
ans += bob[ibob + 1].first - both[iboth - 1].first;
indices.insert(bob[ibob + 1].second);
indices.erase(both[iboth - 1].second);
ibob++;
iboth--;
} else {
break;
}
}
assert((long long)(indices.size()) == m);
while (1) {
vector<pair<long long, long long>> candidates;
if (inone + 1 < nnone && ialice >= 0 && (ialice + 1 + iboth) > k &&
none[inone + 1].first < alice[ialice].first) {
candidates.push_back({none[inone + 1].first - alice[ialice].first, 0});
}
if (inone + 1 < nnone && ibob >= 0 && (ibob + 1 + iboth) > k &&
none[inone + 1].first < bob[ibob].first) {
candidates.push_back({none[inone + 1].first - bob[ibob].first, 1});
}
if ((long long)(candidates.size()) == 0) break;
sort(candidates.begin(), candidates.end());
if ((long long)(candidates.size()) == 2 && iboth - 1 >= 0 &&
none[inone + 1].first - both[iboth - 1].first < candidates[0].first) {
long long curcandidate = none[inone + 1].first - both[iboth - 1].first;
ans += curcandidate;
indices.erase(both[iboth - 1].second);
indices.insert(none[inone + 1].second);
iboth--;
inone++;
} else {
if (candidates[0].first == 0) {
ans += candidates[0].first;
indices.erase(alice[ialice].second);
indices.insert(none[inone + 1].second);
ialice--;
inone++;
} else {
ans += candidates[0].first;
indices.erase(bob[ibob].second);
indices.insert(none[inone + 1].second);
ibob--;
inone++;
}
}
}
if (books < m) {
cout << -1;
} else {
cout << ans;
cout << "\n";
assert((long long)(indices.size()) == m);
for (auto i : indices) {
cout << i << " ";
}
}
return;
}
}
int main() {
cin.sync_with_stdio(false);
cout.sync_with_stdio(false);
cin.tie(NULL);
{
get_ac();
cout << "\n";
}
return 0;
}
| 11 | CPP |
n,k = list(map(int, input().strip().split()))
alice = []
bob = []
both = []
for _ in range(n):
t,a,b = list(map(int, input().strip().split()))
if (a==1 and b==1):
both.append(t)
elif (a==1):
alice.append(t)
elif (b==1):
bob.append(t)
alice.sort()
bob.sort()
both.sort()
done = 0
i=0
j=0
time = 0
i_max = min(len(alice),len(bob))
j_max = len(both)
while ((i<i_max or j<j_max) and done<k):
if (i<i_max and j<j_max):
done += 1
if (alice[i] + bob[i] < both[j]):
time += (alice[i] + bob[i])
i+=1
else:
time += both[j]
j+=1
elif (i<i_max):
done += 1
time += (alice[i] + bob[i])
i += 1
else:
done += 1
time += both[j]
j+=1
if (done < k):
print(-1)
else:
print(time) | 11 | PYTHON3 |
from sys import stdin
n, k = list(map(int, stdin.readline().split()))
alice = []
bob = []
both = []
for _ in range(n):
t, a, b = list(map(int, stdin.readline().split()))
if a == b == 1:
both.append(t)
elif a == 1:
alice.append(t)
elif b == 1:
bob.append(t)
alice = sorted(alice)
bob = sorted(bob)
both = sorted(both)
a, b, c = 0, 0, 0
res = 0
for _ in range(k):
if c >= len(both) and (a >= len(alice) or b >= len(bob)):
res = -1
break
if c >= len(both):
res += alice[a]
res += bob[b]
a += 1
b += 1
elif a >= len(alice) or b >= len(bob):
res += both[c]
c += 1
elif alice[a] + bob[b] < both[c]:
res += alice[a]
res += bob[b]
a += 1
b += 1
elif both[c] <= alice[a] + bob[b]:
res += both[c]
c += 1
print(res)
| 11 | PYTHON3 |
def solution():
aLike = []
bLike = []
bothLike = []
lines, k = input().strip().split()
lines = int(lines)
k = int(k)
for i in range(lines):
cost, isALike, isBLike = input().strip().split()
cost = int(cost)
isALike = (isALike == '1')
isBLike = (isBLike == '1')
if isALike and isBLike:
bothLike.append(cost)
elif isALike:
aLike.append(cost)
elif isBLike:
bLike.append(cost)
aLike.sort()
bLike.sort()
bothLike.sort()
aLike.reverse()
bLike.reverse()
bothLike.reverse()
cost = 0
while len(bothLike) > 0 and k > 0:
if len(aLike) > 0 and len(bLike) > 0:
if bothLike[-1] <= aLike[-1] + bLike[-1]:
cost += bothLike.pop()
k -= 1
else:
cost += aLike.pop()
cost += bLike.pop()
k -= 1
else:
cost += bothLike.pop()
k -= 1
while k > 0:
if len(aLike) > 0 and len(bLike) > 0:
cost += aLike.pop()
cost += bLike.pop()
k -= 1
else:
return -1
return cost
print(solution())
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long N = 3e2 + 5;
int main() {
ios_base::sync_with_stdio(false);
long long n, k, one = 0, two = 0;
cin >> n >> k;
vector<long long> v1, v2, v3;
for (int i = 0; i < n; i++) {
long long x, y, z;
cin >> x >> y >> z;
if (y) one++;
if (z) two++;
if (y && z)
v1.push_back(x);
else if (y)
v2.push_back(x);
else if (z)
v3.push_back(x);
}
if (one < k || two < k) {
cout << -1 << endl;
return 0;
}
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
sort(v3.begin(), v3.end());
long long sum = 0, count1 = k, count2 = k, p = 0, q = 0, r = 0;
int len1 = v1.size(), len2 = v2.size(), len3 = v3.size();
while (count1 > 0 || count2 > 0) {
if (q >= len2 || r >= len3) {
sum += v1[p];
p++;
count1--;
count2--;
} else if (p < len1) {
if (v1[p] <= (v2[q] + v3[r])) {
sum += v1[p];
p++;
count1--;
count2--;
} else {
sum += (v2[q] + v3[r]);
q++;
r++;
count2--;
count1--;
}
} else {
sum += (v2[q] + v3[r]);
q++;
r++;
count2--;
count1--;
}
}
cout << sum;
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5, OO = 0x3f3f3f3f, mod = 1e9 + 7;
int main() {
cin.tie(0);
cin.sync_with_stdio(0);
int n, k;
cin >> n >> k;
vector<int> both, A, B;
for (int i = 0; i < n; i++) {
int t, a, b;
cin >> t >> a >> b;
if (a && b)
both.push_back(t);
else if (a)
A.push_back(t);
else if (b)
B.push_back(t);
}
sort(both.begin(), both.end());
sort(A.begin(), A.end());
sort(B.begin(), B.end());
if (both.size() + A.size() < k || both.size() + B.size() < k) {
cout << "-1\n";
return 0;
}
int mi = min(A.size(), B.size());
for (int i = 0; i < mi; i++) both.push_back(A[i] + B[i]);
sort(both.begin(), both.end());
long long ans = 0;
for (int i = 0; i < k; i++) ans += both[i];
cout << ans << "\n";
return 0;
}
| 11 | CPP |
import bisect
import sys
import math
input = sys.stdin.readline
import functools
import heapq
from collections import defaultdict
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
############ ---- Solution ---- ############
def solve():
[n, m, k] = inlt()
bks = []
for i in range(n):
[t, a, b] = inlt()
bks.append((t, a, b, i+1))
bks.sort(key=lambda x: x[0])
aa_i = [v for v in bks if v[1] == 1 and v[2] == 0]
bb_i = [v for v in bks if v[1] == 0 and v[2] == 1]
cc_i = [v for v in bks if v[1] == 1 and v[2] == 1]
dd_i = [v for v in bks if v[1] == 0 and v[2] == 0]
aa = [0]
bb = [0]
cc = [0]
dd = [0]
for v in bks:
if v[1] == 1 and v[2] == 0:
aa.append(aa[-1] + v[0])
if v[1] == 0 and v[2] == 1:
bb.append(bb[-1] + v[0])
if v[1] == 1 and v[2] == 1:
cc.append(cc[-1] + v[0])
if v[1] == 0 and v[2] == 0:
dd.append(dd[-1] + v[0])
take_a = min(len(aa)-1, k)
take_b = min(len(bb)-1, k)
take_c = 0
take_d = 0
while True:
if take_c >= len(cc)-1:
break
picked = take_a + take_b + take_c + take_d
if take_a + take_c < k or take_b + take_c < k:
take_c += 1
elif take_a > 0 and take_b > 0 and picked > m:
take_c += 1
elif take_a > 0 and take_b > 0 and (aa[take_a-1] + bb[take_b-1] + cc[take_c+1] < aa[take_a] + bb[take_b] + cc[take_c]):
take_c += 1
else:
break
while take_a + take_c > k and take_a > 0:
take_a -= 1
while take_b + take_c > k and take_b > 0:
take_b -= 1
if take_a + take_c < k or take_b + take_c < k or take_a + take_b + take_c + take_d > m:
print(-1)
return
while take_a + take_b + take_c + take_d < m:
cases = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 1, -1, 0]]
cases = [[take_a + case[0], take_b + case[1], take_c + case[2], take_d + case[3]] for case in cases]
flag = False
for i, case in enumerate(cases):
new_take_a = case[0]
new_take_b = case[1]
new_take_c = case[2]
new_take_d = case[3]
if new_take_a < 0 or new_take_a >= len(aa):
continue
if new_take_b < 0 or new_take_b >= len(bb):
continue
if new_take_c < 0 or new_take_c >= len(cc):
continue
if new_take_d < 0 or new_take_d >= len(dd):
continue
if not flag or aa[new_take_a] + bb[new_take_b] + cc[new_take_c] + dd[new_take_d] < aa[take_a] + bb[take_b] + cc[take_c] + dd[take_d]:
take_a, take_b, take_c, take_d = new_take_a, new_take_b, new_take_c, new_take_d
flag = True
res = aa[take_a] + bb[take_b] + cc[take_c] + dd[take_d]
res_arr = []
for i in range(take_a):
res_arr.append(aa_i[i][3])
for i in range(take_b):
res_arr.append(bb_i[i][3])
for i in range(take_c):
res_arr.append(cc_i[i][3])
for i in range(take_d):
res_arr.append(dd_i[i][3])
res_arr.sort()
res_arr = [str(v) for v in res_arr]
print(res)
print(" ".join(res_arr))
return res
if len(sys.argv) > 1 and sys.argv[1].startswith("input"):
f = open("./" + sys.argv[1], 'r')
input = f.readline
res = solve()
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
void solve() {
long long n, k;
cin >> n >> k;
vector<long long> a[3], pre[3];
for (long long i = 0; i < n; i++) {
long long x, y, z;
cin >> x >> y >> z;
if (y & z)
a[0].push_back(x);
else if (y)
a[1].push_back(x);
else if (z)
a[2].push_back(x);
}
auto get_pref = [&](vector<long long>& x, vector<long long>& y) {
y.resize(((long long)(x).size()) + 1);
for (long long i = 0; i < ((long long)(x).size()); i++) {
y[i + 1] = y[i] + x[i];
}
};
for (long long i = 0; i < 3; i++) {
sort((a[i]).begin(), (a[i]).end());
get_pref(a[i], pre[i]);
}
long long ans = INF;
for (long long i = 0; i <= k; i++) {
if (((long long)(a[0]).size()) >= i &&
((long long)(a[1]).size()) >= k - i &&
((long long)(a[2]).size()) >= k - i) {
ans = min(ans, pre[0][i] + pre[1][k - i] + pre[2][k - i]);
}
}
cout << (ans == INF ? -1 : ans);
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long tt = 1;
while (tt--) {
solve();
}
}
| 11 | CPP |
n,k=map(int,input().split())
a,b,t=[],[],[]
for i in range(0,n):
tm,c,d=map(int,input().split())
if c==1 and d==1:
t.append(tm)
elif c==1 and d==0:
a.append(tm)
elif c==0 and d==1:
b.append(tm)
if (len(t)+len(a))<k or (len(t)+len(b))<k:
print(-1)
else:
t.sort()
a.sort()
b.sort()
i=0
j=0
ans=0
fga=0
fgt=0
while(k!=0):
if len(a)<=j or len(b)<=j:
fga=1
break
elif len(t)<=i:
fgt=1
break
elif t[i]>(a[j]+b[j]):
ans+=a[j]+b[j]
j+=1
elif t[i]<=(a[j]+b[j]):
ans+=t[i]
i+=1
k-=1
if fga==1 and fgt==0:
while(k!=0):
ans+=t[i]
i+=1
k-=1
elif fga==0 and fgt!=0:
while(k!=0):
ans+=(a[j]+b[j])
j+=1
k-=1
print(ans)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int read(int &x) { return scanf("%d", &x); }
int read(int &x, int &y) { return scanf("%d%d", &x, &y); }
int read(int &x, int &y, int &z) { return scanf("%d%d%d", &x, &y, &z); }
int read(long long &x) { return scanf("%lld", &x); }
int read(long long &x, long long &y) { return scanf("%lld%lld", &x, &y); }
int read(double &x) { return scanf("%lf", &x); }
char buff[2000010];
int read(string &s) {
int r = scanf("%s", buff);
s = buff;
return r;
}
using namespace std;
struct Groups {
set<pair<long long, long long> > G[10];
long long S[10];
Groups() {
for (int i = 0; i < 10; ++i) S[i] = 0;
}
pair<long long, long long> add(int type, pair<long long, long long> p) {
G[type].insert(p);
S[type] += p.first;
return p;
}
pair<long long, long long> rem(int type, pair<long long, long long> p) {
G[type].erase(p);
S[type] -= p.first;
return p;
}
long long sum(int type) { return S[type]; }
int size(int type) { return G[type].size(); }
pair<long long, long long> getLower(int type) { return *G[type].begin(); }
pair<long long, long long> getHigher(int type) { return *G[type].rbegin(); }
bool contains(int type, pair<long long, long long> v) {
return G[type].count(v) > 0;
}
pair<long long, long long> moveLower(int typeSource, int typeDest) {
auto v = getLower(typeSource);
rem(typeSource, v);
add(typeDest, v);
return v;
}
pair<long long, long long> moveHigher(int typeSource, int typeDest) {
auto v = getHigher(typeSource);
rem(typeSource, v);
add(typeDest, v);
return v;
}
};
int main() {
int TC = 1;
while (TC-- > 0) {
int N, M, K;
read(N, M, K);
Groups G;
vector<int> O(N);
for (int i = 0; i < N; ++i) {
int n, a, b;
read(n, a, b);
O[i] = n;
if (a && b)
G.add(3, pair<long long, long long>(n, i));
else if (a)
G.add(1, pair<long long, long long>(n, i));
else if (b)
G.add(2, pair<long long, long long>(n, i));
else
G.add(4, pair<long long, long long>(n, i));
}
int bi = -1;
long long bs = -1;
int both = G.size(3);
auto adjustGroup = [&](int type, int graveyard, int target, bool updateD) {
while (G.size(type) > 0 && G.size(graveyard) > 0 &&
G.getHigher(type) > G.getLower(graveyard)) {
G.moveHigher(type, graveyard);
}
while (G.size(type) > target && G.size(type) > 0) {
auto v = G.moveHigher(type, graveyard);
if (updateD) {
G.add(4, v);
}
}
while (G.size(type) < target && G.size(graveyard) > 0) {
auto v = G.moveLower(graveyard, type);
if (updateD) {
int pos = G.contains(4, v) ? 4 : 6;
G.rem(pos, v);
}
}
};
auto adjustGroups = [&](int toBoth) {
int needFromAlone = max(0, K - toBoth);
int extras = max(0, M - toBoth - 2 * needFromAlone);
adjustGroup(3, 5, toBoth, true);
adjustGroup(1, 8, needFromAlone, true);
adjustGroup(2, 7, needFromAlone, true);
adjustGroup(4, 6, extras, false);
};
for (int i = 0; i <= both; ++i) {
int needFromAlone = max(0, K - i);
int extras = max(0, M - i - 2 * needFromAlone);
if (extras + 2 * needFromAlone + i != M) continue;
adjustGroups(i);
if (G.size(3) == i && G.size(1) == needFromAlone &&
G.size(2) == needFromAlone && G.size(4) == extras) {
long long ns = G.sum(3) + G.sum(1) + G.sum(2) + G.sum(4);
if (bi == -1 || bs > ns) {
bi = i;
bs = ns;
}
}
}
cout << bs << endl;
if (bs != -1) {
adjustGroups(bi);
int needFromAlone = max(0, K - bi);
int extras = max(0, M - bi - 2 * needFromAlone);
vector<int> I;
assert(G.size(3) == bi && G.size(1) == needFromAlone &&
G.size(2) == needFromAlone && G.size(4) == extras);
for (auto p : G.G[3]) I.push_back(p.second);
for (auto p : G.G[1]) I.push_back(p.second);
for (auto p : G.G[2]) I.push_back(p.second);
for (auto p : G.G[4]) I.push_back(p.second);
sort(I.begin(), I.end());
for (int v : I) cout << v + 1 << " ";
cout << endl;
}
}
}
| 11 | CPP |
import os,io
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,k = list(map(int,input().split()))
z,x,y = [],[],[]
for i in range(n):
t,a,b = list(map(int,input().split()))
if a&b: z.append(t)
elif a: x.append(t)
elif b: y.append(t)
x = sorted(x)
y = sorted(y)
n = min(len(x),len(y))
for i in range(n):
z.append(x[i]+y[i])
if len(z)>=k:
z = sorted(z)[:k]
print(sum(z))
else:
print(-1) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, t, a, b;
int all[200000];
int Alice[200000];
int Bob[200000];
int numAll = 0;
int numAlice = 0;
int numBob = 0;
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> t >> a >> b;
if (a == b && a == 1) {
all[numAll] = t;
numAll++;
} else if (a == 1) {
Alice[numAlice] = t;
numAlice++;
} else if (b == 1) {
Bob[numBob] = t;
numBob++;
}
}
sort(all, all + numAll);
sort(Alice, Alice + numAlice);
sort(Bob, Bob + numBob);
int x = 0;
int y = 0;
int ans = 0;
if (numAll + min(numAlice, numBob) >= k) {
for (int i = 0; i < k; i++) {
if (x >= numAll) {
ans += Alice[y] + Bob[y];
y++;
continue;
}
if (y >= min(numAlice, numBob)) {
ans += all[x];
x++;
continue;
}
if (all[x] <= Alice[y] + Bob[y]) {
ans += all[x];
x++;
} else {
ans += Alice[y] + Bob[y];
y++;
}
}
} else {
ans = -1;
}
cout << ans << endl;
}
| 11 | CPP |
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
N, K = MAP()
A = [INF]
B = [INF]
AB = [INF]
for i in range(N):
t, a, b = MAP()
if a == b == 1:
AB.append(t)
elif a == 1:
A.append(t)
elif b == 1:
B.append(t)
A.sort(reverse=1)
B.sort(reverse=1)
AB.sort(reverse=1)
ans = 0
for i in range(K):
if AB[-1] <= A[-1] + B[-1]:
ans += AB.pop()
else:
ans += A.pop() + B.pop()
if ans >= INF:
print(-1)
exit()
print(ans)
| 11 | PYTHON3 |
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(1000000)
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
#def list2d(a, b, c): return [[c] * b for i in range(a)]
#def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
n,k = ilele()
a = [];b = [];d = []
for i in range(n):
t,x,y = ilele()
if x == y == 1: d.append(t)
elif x==1: a.append(t)
elif y == 1: b.append(t)
a.sort();b.sort()
for i,j in zip(a,b): d.append(i+j)
print(-1) if len(d)<k else print(sum(sorted(d)[:k])) | 11 | PYTHON3 |
from collections import Counter
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")
n, k = gil()
a, b, c = [0], [0], [0]
for _ in range(n):
bk = gil()
if bk[1]&bk[2]:
c.append(bk[0])
elif bk[1]:
a.append(bk[0])
elif bk[2]:
b.append(bk[0])
a.sort(); b.sort(); c.sort()
# print(a, b, c)
for lst in (a, b, c):
for i in range(2, len(lst)):
lst[i] += lst[i-1]
ans = inf; lmt = len(min(a, b,key=len))
# print(lmt)
for i in range(min(len(c), k+1)):
j = k - i
# print(i, j)
if 0 <= j < lmt:
ans = min(c[i] + a[j] + b[j], ans)
print(ans if ans != inf else -1)
| 11 | PYTHON3 |
n, k = map(int, input().split())
books = []
alice = set()
bob = set()
for i in range(n):
books.append([int(i) for i in input().split()])
if books[-1][1] == 1:
alice.add(i)
if books[-1][2] == 1:
bob.add(i)
# if len(alice) <= k < len(bob):
# ans_a = sum([books[i][0] for i in alice])
# print(ans_a)
# elif len(bob) <= k < len(alice):
# ans_b = sum([books[i][0] for i in bob])
# print(ans_b)
# elif len(alice) == k == len(bob):
# temp = alice | bob
# ans = sum([books[i][0] for i in temp])
# print(ans)
# elif len(alice) > k < len(bob):
if len(alice) < k or len(bob) < k:
print(-1)
else:
time, a, b = 0, 0, 0
temp = alice | bob
diff = temp.difference(alice & bob)
temp_alice = []
temp_bob = []
for i in diff:
if i in alice:
temp_alice += [books[i]]
else:
temp_bob += [books[i]]
temp_alice.sort()
temp_bob.sort()
temp_mass = []
for i in range(min(len(temp_bob), len(temp_alice))):
temp_mass.append(
[temp_alice[i][0] + temp_bob[i][0], 1, 1]
)
temp_mass = temp_mass + [books[i] for i in temp if i not in diff]
temp_mass.sort(key=lambda x: (x[1] + x[2], -x[0]), reverse=True)
for i in temp_mass:
time += i[0]
a += i[1]
b += i[2]
if a >= k and b >= k:
break
print(time)
# else:
# print(-1)
| 11 | PYTHON3 |
n,k=map(int,input().split())
a=[]
b=[]
s=[]
ans=0
for i in range(n):
t,x,y=map(int,input().split())
if(x==1 and y==1):
s.append(t)
elif x==1:
a.append(t)
elif y==1:
b.append(t)
s1=len(s)
s2=len(a)
s3=len(b)
if(s1+s3<k):
print(-1)
elif s1+s2<k:
print(-1)
else:
s.sort()
a.sort()
b.sort()
i=0
j=0
v=0
while(k>0):
if(s1==0):
ans+=a[i]+b[i]
k-=1
s2-=1
s3-=1
i+=1
j+=1
elif s2==0 or s3==0:
ans+=s[v]
v+=1
k-=1
s1-=1
else:
k-=1
if(a[i]+b[j]<=s[v]):
s2-=1
s3-=1
ans+=a[i]+b[j]
i+=1
j+=1
else:
ans+=s[v]
v+=1
s1-=1
print(ans)
| 11 | PYTHON3 |
n,k = map(int, input().split())
ali = list()
bob = list()
both = list()
for i in range(n):
l = list(map(int, input().split()))
if l[1] == 1 and l[2] == 1:
both.append(l[0])
elif l[1] == 1:
ali.append(l[0])
elif l[2] == 1:
bob.append(l[0])
ali.sort(reverse=True)
bob.sort(reverse=True)
both.sort(reverse=True)
a = len(ali)
b = len(bob)
if a > b:
a = b
bt = len(both)
if a + bt < k:
print(-1)
else:
count = 0
i,j =-1, -1
a, bt = -a, -bt
while i>=a and j>=bt and k>0:
#print(i,j)
if ali[i] + bob[i] < both[j]:
count += ali[i] + bob[i]
k -= 1
i -= 1
else:
count += both[j]
j -= 1
k -= 1
if j<bt:
while i>=a and k>0:
count += ali[i] + bob[i]
k -= 1
i -= 1
else:
while j>=bt and k >0:
count += both[j]
j -= 1
k -= 1
print(count)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
const int N = (int)5e5 + 7;
const int inf = (int)1e9 + 7;
const int mod = (int)1e9 + 7;
const long long linf = (long long)1e18 + 7;
const int dx[] = {-1, 0, 1, 0, 1, -1, -1, 1};
const int dy[] = {0, 1, 0, -1, 1, -1, 1, -1};
using namespace std;
int n, k, need;
long long p1[N], p2[N];
struct tree {
int cnt[N << 2];
long long t[N << 2];
void upd(int p, int x, int v = 1, int tl = 1, int tr = N) {
if (tl == tr) {
cnt[v] += x;
t[v] = (long long)cnt[v] * tl;
return;
}
int tm = tl + tr >> 1;
if (p <= tm)
upd(p, x, v << 1, tl, tm);
else
upd(p, x, v << 1 | 1, tm + 1, tr);
cnt[v] = cnt[v << 1] + cnt[v << 1 | 1];
t[v] = t[v << 1] + t[v << 1 | 1];
}
long long get(int k, int v = 1, int tl = 1, int tr = N) {
if (tl == tr) {
return k * tl;
}
int tm = tl + tr >> 1;
if (cnt[v << 1] >= k) return get(k, v << 1, tl, tm);
return get(k - cnt[v << 1], v << 1 | 1, tm + 1, tr) + t[v << 1];
}
} t;
void solve() {
cin >> n >> need >> k;
vector<pair<int, int>> l, m, r, free;
for (int i = (1); i <= (n); i++) {
int t, a, b;
cin >> t >> a >> b;
if (a && b)
m.push_back({t, i});
else if (a)
l.push_back({t, i});
else if (b)
r.push_back({t, i});
else
free.push_back({t, i});
}
sort(m.begin(), m.end());
sort(l.begin(), l.end());
sort(r.begin(), r.end());
sort(free.begin(), free.end());
int can1 = min((int)l.size(), (int)r.size()), can2 = (int)m.size();
for (int i = (can1 + 1); i <= ((int)l.size()); i++) {
t.upd(l[i - 1].first, 1);
}
for (int i = (can1 + 1); i <= ((int)r.size()); i++) {
t.upd(r[i - 1].first, 1);
}
for (int i = (1); i <= (can1); i++) {
p1[i] = p1[i - 1] + (l[i - 1].first + r[i - 1].first);
t.upd(l[i - 1].first, 1);
t.upd(r[i - 1].first, 1);
}
for (int i = (1); i <= (can2); i++) {
p2[i] = p2[i - 1] + (m[i - 1].first);
t.upd(m[i - 1].first, 1);
}
for (auto it : free) {
t.upd(it.first, 1);
}
long long mn = linf;
int opt = -1, ptr = 0;
for (int i = (0); i <= (can1); i++) {
int x = i, y = k - x;
if (i) {
t.upd(l[i - 1].first, -1);
t.upd(r[i - 1].first, -1);
}
while (ptr < min(y, can2)) {
++ptr;
t.upd(m[ptr - 1].first, -1);
}
if (y <= can2 && 2 * x + y <= need) {
long long extra = t.get(need - 2 * x - y);
long long sum = p1[x] + p2[y] + extra;
if (mn > sum) {
mn = sum;
opt = i;
}
}
}
if (mn == linf) {
cout << -1 << '\n';
return;
}
vector<int> ans;
int x = opt, y = k - x;
for (int i = (1); i <= (x); i++)
ans.push_back(l[i - 1].second), ans.push_back(r[i - 1].second);
for (int i = (1); i <= (y); i++) ans.push_back(m[i - 1].second);
multiset<pair<int, int>> extra;
for (int i = (x + 1); i <= ((int)l.size()); i++) {
extra.insert(l[i - 1]);
}
for (int i = (x + 1); i <= ((int)r.size()); i++) {
extra.insert(r[i - 1]);
}
for (int i = (y + 1); i <= (can2); i++) {
extra.insert(m[i - 1]);
}
for (auto it : free) extra.insert(it);
int ost = need - 2 * x - y;
while (ost--) {
ans.push_back(extra.begin()->second);
extra.erase(extra.begin());
}
cout << mn << '\n';
for (auto it : ans) {
cout << it << ' ';
}
}
int main() {
ios_base ::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
while (t--) {
solve();
}
exit(0);
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
int i, j, a, b, t;
vector<int> time, temp1, temp2;
for (i = 0; i < n; i++) {
cin >> t >> a >> b;
if (a == 1 && b == 1)
time.push_back(t);
else if (a == 1)
temp1.push_back(t);
else if (b == 1)
temp2.push_back(t);
}
sort(temp1.begin(), temp1.end());
sort(temp2.begin(), temp2.end());
j = min(temp1.size(), temp2.size());
for (i = 0; i < j; i++) time.push_back(temp1[i] + temp2[i]);
sort(time.begin(), time.end());
j = time.size();
if (j < k) {
cout << "-1\n";
} else {
int ans = 0;
for (i = 0; i < k; i++) ans += time[i];
cout << ans << endl;
}
return 0;
}
| 11 | CPP |
import sys
input = sys.stdin.readline
INF = 10 ** 18
n, m, k = map(int, input().split())
B = sorted((tuple(map(int, input().split())) + (i,) for i in range(n)), key=lambda v: v[0])
GB, AB, BB, RB = ([] for _ in range(4))
for t, a, b, i in B:
if a and b: GB.append((t, i))
elif a: AB.append((t, i))
elif b: BB.append((t, i))
else: RB.append((t, i))
N = 1
while N <= 10 ** 4: N *= 2
T = [(0, 0)] * (2 * N)
def comb(a, b): return (a[0] + b[0], a[1] + b[1])
def add_book(t, inc=1):
i = t + N
T[i] = comb(T[i], (t*inc, inc))
while i > 1:
i //= 2
T[i] = comb(T[i*2], T[i*2+1])
def query(x):
assert x >= 0
s = 0
i = 1
while x:
ts, tc = T[i]
if tc < x: return INF
elif tc == x:
s += ts
break
if i >= N:
s += ts // tc * x
break
i *= 2
if T[i][1] < x:
s += T[i][0]
x -= T[i][1]
i += 1
return s
gb_i = 0
gb_t = 0
while gb_i < min(len(GB), m):
gb_t += GB[gb_i][0]
gb_i += 1
cb_i = 0
cb_t = 0
while gb_i + cb_i < k and gb_i + 2 * (cb_i + 1) <= m and cb_i < min(len(AB), len(BB)):
cb_t += AB[cb_i][0] + BB[cb_i][0]
cb_i += 1
for t, _ in GB[gb_i:]: add_book(t)
for t, _ in AB[cb_i:]: add_book(t)
for t, _ in BB[cb_i:]: add_book(t)
for t, _ in RB: add_book(t)
if gb_i + cb_i < k:
print(-1)
sys.exit()
best = (INF, -1, -1)
while True:
best = min(best, (gb_t + cb_t + query(m - 2 * cb_i - gb_i), gb_i, cb_i))
if not gb_i: break
gb_i -= 1
gb_t -= GB[gb_i][0]
add_book(GB[gb_i][0])
if gb_i + cb_i < k:
if cb_i == min(len(AB), len(BB)): break
cb_t += AB[cb_i][0] + BB[cb_i][0]
add_book(AB[cb_i][0], -1)
add_book(BB[cb_i][0], -1)
cb_i += 1
if gb_i + 2 * cb_i > m: break
bs, bi, bj = best
assert bs != INF
ans = []
comps = 0
for t, i in GB[:bi]:
ans.append(i+1)
comps += t
for t, i in AB[:bj]:
ans.append(i+1)
comps += t
for t, i in BB[:bj]:
ans.append(i+1)
comps += t
if bi + 2 * bj < m:
rem = GB[bi:] + AB[bj:] + BB[bj:] + RB
rem.sort()
for t, i in rem[:m - bi - 2 * bj]:
ans.append(i+1)
comps += t
assert comps == bs
print(bs)
print(*ans)
| 11 | PYTHON3 |
import sys
input = sys.stdin.readline
a,b = list(map(int, input().split()))
AL = []
A = []
B = []
for _ in range(a):
n = list(map(int, input().split()))
if n[1]==1 and n[2]==1:
AL.append(n[0])
elif n[1]==1 and n[2]==0:
A.append(n[0])
elif n[1]==0 and n[2]==1:
B.append(n[0])
A.sort()
B.sort()
for k in range(min(len(A), len(B))):
AL.append(A[k] + B[k])
if len(AL) < b:
print(-1)
else:
AL.sort()
ans = sum(AL[:b])
print(ans) | 11 | PYTHON3 |
from typing import List
from heapq import heappop, heappush
# Dictionary. Still using a heap for prioritization, but this should be faster than previous solution.
def readingBooks_easy(n: int, k: int, books: List[int]) -> int:
books.sort(key = lambda x: x[0])
alice = []
bob = []
alice_and_bob = []
for i in range(len(books)):
if (books[i][1] == 1 and books[i][2] == 0):
alice.append(books[i][0])
elif (books[i][1] == 0 and books[i][2] == 1):
bob.append(books[i][0])
elif (books[i][1] == 1 and books[i][2] == 1):
alice_and_bob.append(books[i][0])
alice_or_bob = []
for i in range(min(len(alice), len(bob))):
alice_or_bob.append(alice[i] + bob[i])
heap = []
dic = {}
for i in range(len(alice_and_bob)):
if (alice_and_bob[i] in dic):
dic[alice_and_bob[i]] += 1
else:
dic[alice_and_bob[i]] = 1
heappush(heap, alice_and_bob[i])
for i in range(len(alice_or_bob)):
if (alice_or_bob[i] in dic):
dic[alice_or_bob[i]] += 1
else:
dic[alice_or_bob[i]] = 1
heappush(heap, alice_or_bob[i])
ans = 0
while (k > 0):
if (heap):
popped = heappop(heap)
read = min(dic[popped], k)
cost = read*popped
k -= read
dic[popped] -= read
if (dic[popped] <= 0):
del(dic[popped])
else:
heappush(heap, popped)
ans += cost
else:
return -1
return ans
# Heap (worked like a charm ;) )
# def readingBooks_easy(n: int, k: int, books: List[int]) -> int:
# books.sort(key = lambda x: x[0])
# alice = []
# bob = []
# alice_and_bob = []
# for i in range(len(books)):
# if (books[i][1] == 1 and books[i][2] == 0):
# alice.append(books[i][0])
# elif (books[i][1] == 0 and books[i][2] == 1):
# bob.append(books[i][0])
# elif (books[i][1] == 1 and books[i][2] == 1):
# alice_and_bob.append(books[i][0])
#
# alice_or_bob = []
# for i in range(min(len(alice), len(bob))):
# alice_or_bob.append(alice[i] + bob[i])
#
# heap = []
#
# for i in range(len(alice_and_bob)):
# heappush(heap, alice_and_bob[i])
# for i in range(len(alice_or_bob)):
# heappush(heap, alice_or_bob[i])
#
# ans = 0
# for _ in range(k):
# if (heap):
# ans += heappop(heap)
# else:
# return -1
# return ans
# TLE for when Alice and Bob are reading 20k+ books. Should use a dict to optimize and add all at once.
# def readingBooks_easy(n: int, k: int, books: List[int]) -> int:
# books.sort(key = lambda x: x[0])
# alice = []
# bob = []
# alice_bob = []
# for i in range(len(books)):
# if (books[i][1] == 1 and books[i][2] == 0):
# alice.append(books[i][0])
# elif (books[i][1] == 0 and books[i][2] == 1):
# bob.append(books[i][0])
# elif (books[i][1] == 1 and books[i][2] == 1):
# alice_bob.append(books[i][0])
# ans = 0
# for _ in range(k):
# if ((not alice or not bob) and not alice_bob):
# return -1
# elif ((alice and bob) and not alice_bob):
# ans += alice[0] + bob[0]
# alice.pop(0)
# bob.pop(0)
# elif ((not alice or not bob) and alice_bob):
# ans += alice_bob[0]
# alice_bob.pop(0)
# else:
# if (alice_bob[0] < alice[0] + bob[0]):
# ans += alice_bob[0]
# alice_bob.pop(0)
# else:
# ans += alice[0] + bob[0]
# alice.pop(0)
# bob.pop(0)
# return ans
inputs = list(map(int, input().split(" ")))
n = inputs[0]
k = inputs[1]
books = []
for _ in range(n):
books.append(list(map(int, input().split(" "))))
print(readingBooks_easy(n, k, books)) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
long long n, m, k, t[200005], a[200005], b[200005];
vector<pair<long long, long long> > ta, tb, tboth, tnone;
multiset<long long> second;
int main() {
ios::sync_with_stdio(false);
cin >> n >> m >> k;
for (long long i = 1; i <= n; ++i) cin >> t[i] >> a[i] >> b[i];
long long cnta = 0, cntb = 0, cntboth = 0, cntnone = 0;
for (long long i = 1; i <= n; ++i) {
if (a[i] == 1 && b[i] == 1) {
tboth.push_back(make_pair(t[i], i));
cntboth++;
} else if (a[i] == 1) {
ta.push_back(make_pair(t[i], i));
cnta++;
} else if (b[i] == 1) {
tb.push_back(make_pair(t[i], i));
cntb++;
} else {
tnone.push_back(make_pair(t[i], i));
cntnone++;
}
}
sort(tboth.begin(), tboth.end());
sort(ta.begin(), ta.end());
sort(tb.begin(), tb.end());
sort(tnone.begin(), tnone.end());
long long ans = 1000000007LL * 10000;
long long cboth = 0, cnone = 0, ca = 0, cb = 0, tot = 0;
long long iboth = min(m, cntboth) - 1, ia = -1, ib = -1, inone = -1;
long long besta, bestb, bestboth, bestnone;
for (long long i = 0; i <= iboth; ++i) cboth += tboth[i].first;
tot = iboth + 1;
for (long long i = iboth; i >= -1; --i) {
long long sep = (k - (i + 1));
if (sep > cntb || sep > cnta) continue;
if (2 * sep + iboth + 1 > m) continue;
while (ia < sep - 1) {
ia++;
ca += ta[ia].first;
tot++;
if (tot > m) {
if (ib == -1) {
cnone -= tnone[inone].first;
inone--;
tot--;
} else if (inone == -1) {
cb -= tb[ib].first;
ib--;
tot--;
} else if (ib < sep || tnone[inone].first >= tb[ib].first) {
cnone -= tnone[inone].first;
inone--;
tot--;
} else {
cb -= tb[ib].first;
ib--;
tot--;
}
}
}
while (ib < sep - 1) {
ib++;
cb += tb[ib].first;
tot++;
if (tot > m) {
if (ia == -1) {
cnone -= tnone[inone].first;
inone--;
tot--;
} else if (inone == -1) {
ca -= ta[ia].first;
ia--;
tot--;
} else if (ia < sep || tnone[inone].first >= ta[ia].first) {
cnone -= tnone[inone].first;
inone--;
tot--;
} else {
ca -= ta[ia].first;
ia--;
tot--;
}
}
}
while (tot < m) {
long long mn = 1000000007LL, val = -1;
if (ia + 1 < cnta && (val == -1 || mn >= ta[ia + 1].first)) {
mn = ta[ia + 1].first;
val = 1;
}
if (ib + 1 < cntb && (val == -1 || mn >= tb[ib + 1].first)) {
mn = tb[ib + 1].first;
val = 2;
}
if (inone + 1 < cntnone && (val == -1 || mn >= tnone[inone + 1].first)) {
mn = tnone[inone + 1].first;
val = 3;
}
if (val == 1) {
ia++;
ca += ta[ia].first;
tot++;
} else if (val == 2) {
ib++;
cb += tb[ib].first;
tot++;
} else if (val == 3) {
inone++;
cnone += tnone[inone].first;
tot++;
} else
break;
}
if (tot == m && ans > cboth + ca + cb + cnone) {
ans = cboth + ca + cb + cnone;
bestboth = iboth;
besta = ia;
bestb = ib;
bestnone = inone;
}
if (i >= 0) {
cboth -= tboth[i].first;
tot--;
iboth--;
}
}
if (ans == 1000000007LL * 10000) {
cout << -1 << endl;
return 0;
} else {
cout << ans << "\n";
if (cntboth > 0)
for (long long i = 0; i <= bestboth; ++i) cout << tboth[i].second << " ";
if (cnta > 0)
for (long long i = 0; i <= besta; ++i) cout << ta[i].second << " ";
if (cntb > 0)
for (long long i = 0; i <= bestb; ++i) cout << tb[i].second << " ";
if (cntnone > 0)
for (long long i = 0; i <= bestnone; ++i) cout << tnone[i].second << " ";
cout << endl;
}
}
| 11 | CPP |
import math
import collections
import sys
def inpu():
return input().split(' ')
def inti(a):
for i in range(len(a)):
a[i] = int(a[i])
return a
def inp():
a = inpu()
a = inti(a)
return a
a = inp()
n, k = a[0], a[1]
bob = []
alice = []
common = []
for i in range(n):
a = inp()
if a[1] == 1 and a[2] == 1:
common.append(a[0])
elif a[1] == 1 and a[2] == 0:
bob.append(a[0])
elif a[1] == 0 and a[2] == 1:
alice.append(a[0])
bob.sort()
alice.sort()
common.sort()
l1 = len(bob)
l2 = len(alice)
l3 = len(common)
if l1+l3 < k or l2 + l3 < k:
print(-1)
exit(0)
bobptr = 0
aliceptr = 0
commonptr = 0
cost = 0
while k > 0:
if (commonptr >= l3) or (bobptr < l1 and aliceptr < l2 and commonptr < l3 and bob[bobptr] + alice[aliceptr] < common[commonptr]):
cost = cost + bob[bobptr] + alice[aliceptr]
k -= 1
bobptr += 1
aliceptr += 1
else:
cost = cost + common[commonptr]
commonptr += 1
k -= 1
print(cost)
| 11 | PYTHON3 |
#!/usr/bin/env pypy3
from sys import stdin, stdout
def input():
return stdin.readline().strip()
N, K = input().split(' ')
N = int(N)
K = int(K)
alice_only = []
bob_only = []
both = []
for _ in range(N):
t, a, b = input().split(' ')
t = int(t)
a = int(a)
b = int(b)
if a == 0 and b == 0: continue
if a == 1 and b == 1: both += [t]
if a == 1 and b == 0: alice_only += [t]
if a == 0 and b == 1: bob_only += [t]
hybrid = []
alice_only = sorted(alice_only)
bob_only = sorted(bob_only)
for a, b in zip(alice_only, bob_only):
hybrid += [a + b]
candidates = sorted(both + hybrid)
if len(candidates) < K:
print(-1)
else:
print(sum(candidates[0:K]))
| 11 | PYTHON3 |
# from debug import debug
import sys;input = sys.stdin.readline
n, k = map(int, input().split())
s1, s2, s3 = [], [], []
for i in range(n):
a, b, c = map(int, input().split())
if b == c == 1: s1.append(a)
elif b == 1: s2.append(a)
elif c == 1: s3.append(a)
s1.sort(); s2.sort(); s3.sort();
i, j, l = 0, 0, 0
days = 0
likes = 0
n1, n2, n3 = len(s1), len(s2), len(s3)
while likes < k:
if i == n1:
if j == n2 or l == n3: break
likes += 1
days += s2[j]+s3[l]
j+=1; l+=1
elif j == n2:
if i == n1: break
likes += 1
days += s1[i]
i+=1
elif l == n3:
if i == n1: break
likes+=1
days+=s1[i]
i+=1
else:
if s1[i] >= s2[j]+s3[l]:
days += s2[j]+s3[l]
j+=1; l+=1
likes += 1
else:
days += s1[i]
i+=1
likes += 1
if i == n1 and j == n2 and l == n3: break
if likes<k: print(-1)
else: print(days)
| 11 | PYTHON3 |
import sys
import math
import collections
import heapq
def set_debug(debug_mode=False):
if debug_mode:
fin = open('input.txt', 'r')
sys.stdin = fin
def int_input():
return list(map(int, input().split()))
if __name__ == '__main__':
# set_debug(True)
# t = int(input())
t = 1
for ti in range(1, t + 1):
n, k = int_input()
both = []
Ab = []
Bb = []
A = 0
B = 0
for _ in range(n):
t, a, b = int_input()
if a == 1 and b == 1:
both.append(t)
elif a == 1:
Ab.append(t)
elif b == 1:
Bb.append(t)
Ab.sort()
Bb.sort()
for i in range(min(len(Ab), len(Bb))):
both.append(Ab[i] + Bb[i])
print(-1 if len(both) < k else sum(sorted(both)[:k]))
| 11 | PYTHON3 |
n,k=map(int,input().split())
ar=[];a1=[];b1=[]
for _ in range(n):
t,a,b=map(int,input().split())
if a==1 and b==1:
ar.append(t)
elif a==1 and b==0:
a1.append(t)
elif b==1 and a==0:
b1.append(t)
a1=sorted(a1);b1=sorted(b1)
for i in range(min(len(a1),len(b1))):
ar.append(a1[i]+b1[i])
ar=sorted(ar)
if len(ar)<k:
print(-1)
else:
print(sum(ar[:k])) | 11 | PYTHON3 |
from math import inf
n,k=map(int,input().split())
dic={'11':[],'10':[],'01':[]}
for _ in range(n):
a,b,c=input().split()
a=int(a)
if b=='1' or c=='1':
dic[b+c].append(a)
dic['11'].sort()
dic['10'].sort()
dic['01'].sort()
sums={'11':[0],'10':[0],'01':[0]}
for i in dic:
for j in dic[i]:
sums[i].append(sums[i][-1]+j)
#print(sums)
total=inf
for i in range(min(k+1,len(sums['11']))):
number=k-i
#print(i,number)
if number<len(sums['10']) and number<len(sums['01']):
total=min(total,sums['11'][i]+sums['10'][number]+sums['01'][number])
if total==inf:
print(-1)
else:
print(total) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const char nl = '\n';
const int MAX_N = 100011;
const long long INF = (1LL << 50) + 123;
const long long MOD = 1000000007;
const long double PI = 4 * atan((long double)1);
template <typename T>
bool ckmin(T& a, const T& b) {
return a > b ? a = b, 1 : 0;
}
template <typename T>
bool ckmax(T& a, const T& b) {
return b > a ? a = b, 1 : 0;
}
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
const int MX = 1 << 20;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m, k;
cin >> n >> m >> k;
vector<pair<int, int> > both, left, right;
int t, a, b;
set<pair<int, int> > rest;
for (int i = 0; i < n; i++) {
cin >> t >> a >> b;
if (a && b)
both.push_back({t, i});
else if (a)
left.push_back({t, i});
else if (b)
right.push_back({t, i});
rest.insert({t, i});
}
set<pair<int, int> > rCopy = rest;
sort(left.begin(), left.end());
sort(right.begin(), right.end());
sort(both.begin(), both.end());
int sm = min((int)left.size(), (int)right.size());
if ((int)both.size() + sm < k) {
cout << -1 << nl;
return 0;
}
long long bothSum = 0;
int bothCount = 0;
for (int i = 0; i < min(k, (int)both.size()); i++) {
bothSum += both[i].first;
bothCount++;
rest.erase(rest.find(both[i]));
}
long long ans = INF;
long long curAns = 0;
long long rSum = 0;
set<pair<int, int> > r;
while ((int)r.size() < m - k) {
if ((int)rest.size() == 0) break;
r.insert(*rest.begin());
rSum += rest.begin()->first;
rest.erase(rest.begin());
}
int bestIdx = -1;
if (bothCount == k && (int)r.size() == m - k)
if (ckmin(ans, bothSum + rSum)) bestIdx = k;
int lrCount = 0;
for (int i = (k)-1; i >= 0; i--) {
if (k - i - 1 >= sm || 2 * (k - i) + i > m) break;
if (i < (int)both.size()) {
bothSum -= both[i].first;
rest.insert(both[i]);
bothCount--;
}
curAns += left[k - i - 1].first + right[k - i - 1].first;
lrCount += 2;
assert(rest.find(left[k - i - 1]) != rest.end() ||
r.find(left[k - i - 1]) != r.end());
assert(rest.find(right[k - i - 1]) != rest.end() ||
r.find(right[k - i - 1]) != r.end());
if (rest.find(left[k - i - 1]) != rest.end())
rest.erase(rest.find(left[k - i - 1]));
if (rest.find(right[k - i - 1]) != rest.end())
rest.erase(rest.find(right[k - i - 1]));
if (r.find(left[k - i - 1]) != r.end())
r.erase(r.find(left[k - i - 1])), rSum -= left[k - i - 1].first;
if (r.find(right[k - i - 1]) != r.end())
r.erase(r.find(right[k - i - 1])), rSum -= right[k - i - 1].first;
while ((int)r.size() < m - 2 * (k - i) - i) {
if ((int)rest.size() == 0) break;
r.insert(*rest.begin());
rSum += rest.begin()->first;
rest.erase(rest.begin());
}
while ((int)r.size() > m - 2 * (k - i) - i) {
rest.insert(*r.rbegin());
rSum -= r.rbegin()->first;
r.erase(--r.end());
}
if (bothCount == i && lrCount == 2 * (k - i) &&
bothCount + lrCount + (int)r.size() == m) {
if (ckmin(ans, bothSum + curAns + rSum)) bestIdx = i;
}
}
if (bestIdx == -1)
cout << -1 << nl;
else {
cout << ans << nl;
for (int i = 0; i < bestIdx; i++) {
cout << both[i].second + 1 << " ";
rCopy.erase(rCopy.find(both[i]));
}
for (int i = 0; i < k - bestIdx; i++) {
cout << left[i].second + 1 << " " << right[i].second + 1 << " ";
rCopy.erase(rCopy.find(left[i]));
rCopy.erase(rCopy.find(right[i]));
}
int count = 0;
assert(bestIdx + 2 * (k - bestIdx) <= m);
for (auto& a : rCopy) {
if (count + bestIdx + 2 * (k - bestIdx) == m) break;
count++;
cout << a.second + 1 << " ";
}
cout << nl;
assert(count + bestIdx + 2 * (k - bestIdx) == m);
}
return 0;
}
| 11 | CPP |
n,k = map(int, input().split())
t=[]
a=[]
b=[]
for i in range(n):
t1,a1,b1 = map(int, input().split())
if(a1==1 and b1==1):
t.append(t1)
elif(a1==1):
a.append(t1)
elif(b1==1):
b.append(t1)
a.sort()
b.sort()
k1=min(len(a),len(b))
for i in range(k1):
t.append(a[i]+b[i])
ans=0
t.sort()
if(len(t)<k):
print("-1")
else:
print(sum(t[:k]))
| 11 | PYTHON3 |
# https://codeforces.com/contest/1374/problem/E1
# Дорешевание
import sys
from collections import deque
reader = (tuple(map(int, line.split())) for line in sys.stdin)
both, alice, bob = [], [], []
n, k = next(reader)
for _ in range(n):
value, alice_fl, bob_fl = next(reader)
if alice_fl and bob_fl:
both.append(value)
if alice_fl and not bob_fl:
alice.append(value)
if not alice_fl and bob_fl:
bob.append(value)
both.sort()
both = deque(both)
alice.sort()
alice = deque(alice)
bob.sort()
bob = deque(bob)
cnt_alice, cnt_bob = 0, 0
result = 0
while cnt_alice < k and cnt_bob < k:
if len(both) > 0 and len(alice) > 0 and len(bob) > 0:
if both[0] <= alice[0] + bob[0]:
result += both.popleft()
else:
result += alice.popleft() + bob.popleft()
cnt_alice += 1
cnt_bob += 1
else:
if len(alice) == 0 or len(bob) == 0:
if len(both) > 0:
result += both.popleft()
cnt_alice += 1
cnt_bob += 1
else:
result = -1
break
else: # alice != 0 and bob != 0 => both = 0
result += alice.popleft()
result += bob.popleft()
cnt_alice += 1
cnt_bob += 1
print(result) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k;
cin >> n >> k;
long long arr[n + 1];
long long a, b, c;
vector<long long> A, B, common;
for (long long i = 0; i < n; i++) {
cin >> a >> b >> c;
if (b == 1 && c == 1) {
common.push_back(a);
} else if (b == 1) {
A.push_back(a);
} else if (c == 1) {
B.push_back(a);
}
}
sort(common.begin(), common.end());
sort(A.begin(), A.end());
sort(B.begin(), B.end());
long long pc = 0, pa = 0, pb = 0;
if ((long long)(common.size() + min(A.size(), B.size())) < k) {
cout << "-1\n";
return 0;
}
long long cnt = 0, res = 0;
common.push_back(INT_MAX);
A.push_back(INT_MAX);
B.push_back(INT_MAX);
while (pc < (long long)common.size() || (pa < A.size() && pb < B.size())) {
if (cnt == k) break;
if (common[pc] < A[pa] + B[pb]) {
res += common[pc];
pc++;
cnt++;
} else {
res += (A[pa] + B[pb]);
pa++;
pb++;
cnt++;
}
}
if (cnt == k)
cout << res;
else
cout << "-1";
return 0;
}
| 11 | CPP |
import math
def gcd(a,b):
if (b == 0):
return a
return gcd(b, a%b)
def lcm(a,b):
return (a*b) / gcd(a,b)
def bs(arr, l, r, x):
while l <= r:
mid = l + (r - l)//2;
if(arr[mid]==x):
return arr[mid]
elif(arr[mid]<x):
l = mid + 1
else:
r = mid - 1
return -1
def swap(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
t = 1
for _ in range(t):
n,k = map(int,input().split())
x = []
c=0
ans=0
y01 = []
y10 = []
y11 = []
for i in range(n):
tt,a,b = map(int,input().split())
if(a==1 and b==1):
y11.append(tt)
elif(a==1 and b==0):
y10.append(tt)
elif(a==0 and b==1):
y01.append(tt)
y11.sort()
y01.sort()
y10.sort()
f=0
i = 0
j = 0
while(k):
k-=1
if(i<len(y11) and (j<len(y01) and j<len(y10))):
if(y11[i]<y01[j]+y10[j]):
ans+=y11[i]
i+=1
else:
ans+=y10[j]+y01[j]
j+=1
elif(i<len(y11)):
ans+=y11[i]
i+=1
elif((j<len(y01) and j<len(y10))):
ans+=y10[j]+y01[j]
j+=1
else:
f=1
if(f):
print(-1)
continue
print(ans)
| 11 | PYTHON3 |
import sys
def solve():
n, k = map(int, sys.stdin.readline().split())
list_book = [[],[],[]]# together, Alice, Bob
count = [0,0,0]
for _ in range(n):
t, a, b = map(int, sys.stdin.readline().split())
if a and b:
list_book[0].append(t)
count[0]+=1
elif a:
list_book[1].append(t)
count[1]+=1
elif b:
list_book[2].append(t)
count[2]+=1
if count[0] + min(count[1], count[2]) < k:
print(-1)
return
list_book[0].sort(reverse=True)
list_book[1].sort(reverse=True)
list_book[2].sort(reverse=True)
result = 0
book = k # The book which they mush read.
result = 0
for _ in range(k):
next_time = 1000000000000000000000
token = 0
if list_book[1] and list_book[2]:
next_time = list_book[1][-1] + list_book[2][-1]
if list_book[0]:
if next_time > list_book[0][-1]:
next_time = list_book[0][-1]
token = 1
if token:
list_book[0].pop()
else:
list_book[1].pop()
list_book[2].pop()
result += next_time
print(result)
solve() | 11 | PYTHON3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.