text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` n = int(input()) a = list(map(int,input().split())) for i in range(n): a[i] = (a[i],-i) a.sort() m = int(input()) for j in range(m): t = list(map(int, input().split())) k = t[0] p = t[1] print(sorted(a[-k:], key = lambda x: -x[1])[p-1][0]) ``` Yes
85,800
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` n = int(input()) s = list(map(int, input().split())) for i in range(n): s[i] = (s[i], i) mx = sorted(s, key=lambda y: y[0], reverse=True) m = int(input()) for i in range(m): k, pos = map(int, input().split()) pos -= 1 a = 0 last = mx[0][0] res = [] d = dict() d2 = dict() for x in range(k): if mx[x][0] not in d: d[mx[x][0]] = 1 else: d[mx[x][0]] += 1 for x in range(n): if mx[x][0] != last: a += 1 last = mx[x][0] if a == k: break if mx[x][0] not in d2: d2[mx[x][0]] = [mx[x][1]] else: d2[mx[x][0]].append(mx[x][1]) for a in list(d.keys()): d2[a].sort() for j in range(d[a]): res.append((a, d2[a][j])) res = sorted(res, key=lambda y: y[1]) print(res[pos][0]) ``` Yes
85,801
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` n = int(input()) data = list(map(int, input().split())) m = int(input()) for _ in range(m): k, pos = map(int, input().split()) s = data[:] ans = [] for i in range(k): x = s.index(max(s)) ans.append(x) s[x] = -1 ans.sort() print(data[ans[pos - 1]]) ``` Yes
85,802
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` n=int(input()) a=[int(i) for i in input().split()] b=sorted(a) c=[] c.append(a) for i in range(1,n+1): k=len(c[i-1])-1-c[i-1][::-1].index(b[i-1]) c.append(c[i-1][0:k]+c[i-1][k+1::]) m=int(input()) for i in range (m): k,pos=map(int,input().split()) print (c[len(c)-k-1][pos-1]) ``` Yes
85,803
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` n = int(input()) arr = [int(i) for i in input().split()] sor = [[arr[i], n - i] for i in range(n)] sor.sort() m = int(input()) print (sor) for i in range(m): op = [] [q, index] = [int(i) for i in input().split()] for j in range(q): op.append(n - sor[-1-j][1]) print (op) op.sort() print(arr[op[index - 1]]) ``` No
85,804
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` from sys import stdin,stdout from math import gcd,sqrt,factorial,pi from collections import deque,defaultdict input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') L=lambda:list(R()) P=lambda x:stdout.write(x) lcm=lambda x,y:(x*y)//gcd(x,y) hg=lambda x,y:((y+x-1)//x)*x pw=lambda x:1 if x==1 else 1+pw(x//2) chk=lambda x:chk(x//2) if not x%2 else True if x==1 else False sm=lambda x:(x**2+x)//2 N=10**9+7 n=I() *a,=R() d={} for i in a: if i not in d:d[i]=0 d[i]+=1 for _ in range(I()): k,p=R() m=[] cnt=0 for i in sorted(d,reverse=True): cnt+=d[i] m+=i, if cnt>=k:break m=[i for i in a if i in m] ans=m[:k] sm=sum(ans) for i in range(k,len(m)): v=sum(m[k-i+1:i+1]) if v>sm: sm=v ans=m[k-i+1:i+1] elif v==sm and m[k-i+1:i+1]<ans: ans=m[k-i+1:i+1] print(ans[p-1]) ``` No
85,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` def mergesort(l, r, arr, pos): if r - l == 1: return arr, pos m = (l + r) // 2 arr, pos = mergesort(l, m, arr, pos) arr, pos = mergesort(m, r, arr, pos) c = [0 for i in range(r)] d = [0 for i in range(r)] poi_a = l poi_b = m for i in range(l, r): if poi_a == m: c[i] = arr[poi_b] d[i] = pos[poi_b] poi_b += 1 elif poi_b == r: c[i] = arr[poi_a] d[i] = pos[poi_a] poi_a += 1 elif a[poi_a] > arr[poi_b]: c[i] = arr[poi_a] d[i] = pos[poi_a] poi_a += 1 else: c[i] = arr[poi_b] d[i] = pos[poi_b] poi_b += 1 for i in range(l, r): arr[i] = c[i] pos[i] = d[i] return arr, pos n = int(input()) a = list(map(int, input().split())) p = [i for i in range(n)] temp = a[:] a, p = mergesort(0, n, a, p) pref = [] i = 0 while i < n: j = i + 1 if j < n and a[i] == a[j]: j += 1 pref.append([i, j]) i = j for m in range(int(input())): k, pos = map(int, input().split()) for t in range(len(pref)): if pref[t][0] <= k - 1 < pref[t][1]: i = pref[t][0] j = pref[t][1] l = k - 1 - i + 1 m = sorted(p[i:j]) res = sorted(m[:l] + p[:i]) print(temp[res[pos - 1]]) ``` No
85,806
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) a1 = sorted(a, key=lambda x: -x) m = int(input()) for i in range(m): k, p = list(map(int, input().split())) c = {} s = [] for j in range(n+1): s.append({}) pos = {} for j in range(n): c[a1[j]] = 0 s[0][a[j]] = 0 pos[a1[j]] = [] for j in range(n): s[0][a[j]] += 1 for j in range(n): for t in range(n): s[j+1][a[t]] = s[j][a[t]] s[j+1][a[j]] -= 1 b = [] for j in range(k): c[a1[j]]+=1 ns = [] for j in range(n): if c[a[j]] ^ 0: pos[a[j]].append(j) if len(pos[a[j]]) == 1: ns.append(a[j]) ns = sorted(ns) counter = 0 ans = [] minpos = 0 while counter ^ k: flag = 0 for j in range(len(ns)): c[ns[j]] -= 1 flag1 = 0 for f in range(len(pos[ns[j]])): if minpos <= pos[ns[j]][f]: for u in range(len(ns)): if s[pos[ns[j]][f]+1][ns[u]] < c[ns[u]]: flag1 = 1 break if flag1 == 1: break else: minpos = pos[ns[j]][f]+1 flag = 1 break if flag == 1: ans.append(ns[j]) counter += 1 break else: c[ns[j]] += 1 print(ans[p-1]) ``` No
85,807
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0 Tags: binary search, data structures Correct Solution: ``` n = int(input()) a = [0] + list(map(int, input().split())) pos, pb, ps = [[0] * (n + 1) for x in range(3)] def add(bit, i, val): while i <= n: bit[i] += val i += i & -i def sum(bit, i): res = 0 while i > 0: res += bit[i] i -= i & -i return res def find(bit, sum): i, t = 0, 0 if sum == 0: return 0 for k in range(17, -1, -1): i += 1 << k if i <= n and t + bit[i] < sum: t += bit[i] else: i -= 1 << k return i + 1 for i in range(1, n + 1): pos[a[i]] = i invSum = 0 totalSum = 0 for i in range(1, n + 1): totalSum += pos[i] invSum += i - sum(pb, pos[i]) - 1 add(pb, pos[i], 1) add(ps, pos[i], pos[i]) mid = find(pb, i // 2) if i % 2 == 1: mid2 = find(pb, i // 2 + 1) seqSum = (i + 1) * (i // 2) // 2 else: mid2 = mid seqSum = i * (i // 2) // 2 leftSum = sum(ps, mid) rightSum = totalSum - sum(ps, mid2) print(rightSum - leftSum - seqSum + invSum, end=" ") ```
85,808
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0 Tags: binary search, data structures Correct Solution: ``` from bisect import bisect_right, bisect_left # instead of AVLTree class BITbisect(): def __init__(self, InputProbNumbers): # 座圧 self.ind_to_co = [-10**18] self.co_to_ind = {} for ind, num in enumerate(sorted(list(set(InputProbNumbers)))): self.ind_to_co.append(num) self.co_to_ind[num] = ind+1 self.max = len(self.co_to_ind) self.data = [0]*(self.max+1) def __str__(self): retList = [] for i in range(1, self.max+1): x = self.ind_to_co[i] if self.count(x): c = self.count(x) for _ in range(c): retList.append(x) return "[" + ", ".join([str(a) for a in retList]) + "]" def __getitem__(self, key): key += 1 s = 0 ind = 0 l = self.max.bit_length() for i in reversed(range(l)): if ind + (1<<i) <= self.max: if s + self.data[ind+(1<<i)] < key: s += self.data[ind+(1<<i)] ind += (1<<i) if ind == self.max or key < 0: raise IndexError("BIT index out of range") return self.ind_to_co[ind+1] def __len__(self): return self._query_sum(self.max) def __contains__(self, num): if not num in self.co_to_ind: return False return self.count(num) > 0 # 0からiまでの区間和 # 左に進んでいく def _query_sum(self, i): s = 0 while i > 0: s += self.data[i] i -= i & -i return s # i番目の要素にxを足す # 上に登っていく def _add(self, i, x): while i <= self.max: self.data[i] += x i += i & -i # 値xを挿入 def push(self, x): if not x in self.co_to_ind: raise KeyError("The pushing number didnt initialized") self._add(self.co_to_ind[x], 1) # 値xを削除 def delete(self, x): if not x in self.co_to_ind: raise KeyError("The deleting number didnt initialized") if self.count(x) <= 0: raise ValueError("The deleting number doesnt exist") self._add(self.co_to_ind[x], -1) # 要素xの個数 def count(self, x): return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1) # 値xを超える最低ind def bisect_right(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_right(self.ind_to_co, x) - 1 return self._query_sum(i) # 値xを下回る最低ind def bisect_left(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_left(self.ind_to_co, x) if i == 1: return 0 return self._query_sum(i-1) import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) Ind = [0]*(N+1) for i, a in enumerate(A): Ind[a] = i+1 Bit = BITbisect(list(range(N+1))) ans = [0] Bit.push(Ind[1]) a = 0 for n in range(2, N+1): ind = Ind[n] f = Bit.bisect_left(ind) #print(Bit) l = len(Bit) if l%2 == 0: if f == l//2: a += l//2-l//2 elif f < l//2: p1 = Bit[l//2-1] a += (p1-ind-1) - (l//2-1) + l-f else: p2 = Bit[l//2] a += (ind-p2-1) - (l//2-1) + l-f else: p1 = Bit[l//2] #print(f, p1, ind, l) if f <= l//2: a += (p1-ind-1) - l//2 + l-f else: a += (ind-p1-1) - l//2 + l-f ans.append(a) Bit.push(ind) print(*ans, sep=" ") ```
85,809
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0 Submitted Solution: ``` n = int(input()) a = [0] + list(map(int, input().split())) pos, bit = [[0] * (n+1), [0] * (n+1)] def add(i): while i <= n: bit[i] += 1 i += i & -i def sum(i): res = 0 while i > 0: res += bit[i] i -= i & -i return res for i in range(1, n+1): pos[a[i]] = i Max, Min, invSum = [0, n, 0] for i in range(1, n+1): Max = max(Max, pos[i]) Min = min(Min, pos[i]) invSum += i - sum(pos[i]) - 1 print(Max - Min - i + invSum + 1, end=' ') add(pos[i]) ``` No
85,810
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0 Submitted Solution: ``` from bisect import bisect_right, bisect_left # instead of AVLTree class BITbisect(): def __init__(self, InputProbNumbers): # 座圧 self.ind_to_co = [-10**18] self.co_to_ind = {} for ind, num in enumerate(sorted(list(set(InputProbNumbers)))): self.ind_to_co.append(num) self.co_to_ind[num] = ind+1 self.max = len(self.co_to_ind) self.data = [0]*(self.max+1) def __str__(self): retList = [] for i in range(1, self.max+1): x = self.ind_to_co[i] if self.count(x): c = self.count(x) for _ in range(c): retList.append(x) return "[" + ", ".join([str(a) for a in retList]) + "]" def __getitem__(self, key): key += 1 s = 0 ind = 0 l = self.max.bit_length() for i in reversed(range(l)): if ind + (1<<i) <= self.max: if s + self.data[ind+(1<<i)] < key: s += self.data[ind+(1<<i)] ind += (1<<i) if ind == self.max or key < 0: raise IndexError("BIT index out of range") return self.ind_to_co[ind+1] def __len__(self): return self._query_sum(self.max) def __contains__(self, num): if not num in self.co_to_ind: return False return self.count(num) > 0 # 0からiまでの区間和 # 左に進んでいく def _query_sum(self, i): s = 0 while i > 0: s += self.data[i] i -= i & -i return s # i番目の要素にxを足す # 上に登っていく def _add(self, i, x): while i <= self.max: self.data[i] += x i += i & -i # 値xを挿入 def push(self, x): if not x in self.co_to_ind: raise KeyError("The pushing number didnt initialized") self._add(self.co_to_ind[x], 1) # 値xを削除 def delete(self, x): if not x in self.co_to_ind: raise KeyError("The deleting number didnt initialized") if self.count(x) <= 0: raise ValueError("The deleting number doesnt exist") self._add(self.co_to_ind[x], -1) # 要素xの個数 def count(self, x): return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1) # 値xを超える最低ind def bisect_right(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_right(self.ind_to_co, x) - 1 return self._query_sum(i) # 値xを下回る最低ind def bisect_left(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_left(self.ind_to_co, x) if i == 1: return 0 return self._query_sum(i-1) import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) Ind = [0]*(N+1) for i, a in enumerate(A): Ind[a] = i+1 Bit = BITbisect(list(range(N+1))) ans = [0] Bit.push(Ind[1]) a = 0 for n in range(2, N+1): ind = Ind[n] f = Bit.bisect_left(ind) #print(Bit) l = len(Bit) if l%2 == 0: if f == l//2: a += l//2 elif f < l//2: p1 = Bit[l//2-1] a += (p1-ind-1) - (l//2-1) + l-f else: p2 = Bit[l//2] a += (ind-p2-1) - (l//2-1) + l-f else: p1 = Bit[l//2] #print(f, p1, ind, l) if f <= l//2: a += (p1-ind-1) - l//2 + l-f else: a += (ind-p1-1) - l//2 + l-f ans.append(a) Bit.push(ind) print(*ans, sep=" ") ``` No
85,811
Provide tags and a correct Python 3 solution for this coding contest problem. There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1). You're given k subsets A_1, …, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 ≤ i_1 < i_2 < i_3 ≤ k, A_{i_1} ∩ A_{i_2} ∩ A_{i_3} = ∅. In one operation, you can choose one of these k subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation. Let m_i be the minimum number of operations you have to do in order to make the i first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1 and n), they can be either off or on. You have to compute m_i for all 1 ≤ i ≤ n. Input The first line contains two integers n and k (1 ≤ n, k ≤ 3 ⋅ 10^5). The second line contains a binary string of length n, representing the initial state of each lamp (the lamp i is off if s_i = 0, on if s_i = 1). The description of each one of the k subsets follows, in the following format: The first line of the description contains a single integer c (1 ≤ c ≤ n) — the number of elements in the subset. The second line of the description contains c distinct integers x_1, …, x_c (1 ≤ x_i ≤ n) — the elements of the subset. It is guaranteed that: * The intersection of any three subsets is empty; * It's possible to make all lamps be simultaneously on using some operations. Output You must output n lines. The i-th line should contain a single integer m_i — the minimum number of operations required to make the lamps 1 to i be simultaneously on. Examples Input 7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 Output 1 2 3 3 3 3 3 Input 8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 Output 1 1 1 1 1 1 4 4 Input 5 3 00011 3 1 2 3 1 4 3 3 4 5 Output 1 1 1 1 1 Input 19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 Output 0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 Note In the first example: * For i = 1, we can just apply one operation on A_1, the final states will be 1010110; * For i = 2, we can apply operations on A_1 and A_3, the final states will be 1100110; * For i ≥ 3, we can apply operations on A_1, A_2 and A_3, the final states will be 1111111. In the second example: * For i ≤ 6, we can just apply one operation on A_2, the final states will be 11111101; * For i ≥ 7, we can apply operations on A_1, A_3, A_4, A_6, the final states will be 11111111. Tags: dfs and similar, dsu, graphs Correct Solution: ``` from sys import stdin input = stdin.readline n , k = [int(i) for i in input().split()] pairs = [i + k for i in range(k)] + [i for i in range(k)] initial_condition = list(map(lambda x: x == '1',input().strip())) data = [i for i in range(2*k)] constrain = [-1] * (2*k) h = [0] * (2*k) L = [1] * k + [0] * k dp1 = [-1 for i in range(n)] dp2 = [-1 for i in range(n)] for i in range(k): input() inp = [int(j) for j in input().split()] for s in inp: if dp1[s-1] == -1:dp1[s-1] = i else:dp2[s-1] = i pfsums = 0 ans = [] def remove_pfsum(s1): global pfsums if constrain[s1] == 1: pfsums -= L[s1] elif constrain[pairs[s1]] == 1: pfsums -= L[pairs[s1]] else: pfsums -= min(L[s1],L[pairs[s1]]) def sh(i): while i != data[i]: i = data[i] return i def upd_pfsum(s1): global pfsums if constrain[s1] == 1: pfsums += L[s1] elif constrain[pairs[s1]] == 1: pfsums += L[pairs[s1]] else: pfsums += min(L[s1],L[pairs[s1]]) def ms(i,j): i = sh(i) ; j = sh(j) cons = max(constrain[i],constrain[j]) if h[i] < h[j]: data[i] = j L[j] += L[i] constrain[j] = cons return j else: data[j] = i if h[i] == h[j]: h[i] += 1 L[i] += L[j] constrain[i] = cons return i for i in range(n): if dp1[i] == -1 and dp2[i] == -1: pass elif dp2[i] == -1: s1 = sh(dp1[i]) remove_pfsum(s1) constrain[s1] = 0 if initial_condition[i] else 1 constrain[pairs[s1]] = 1 if initial_condition[i] else 0 upd_pfsum(s1) else: s1 = sh(dp1[i]) ; s2 = sh(dp2[i]) if s1 == s2 or pairs[s1] == s2: pass else: remove_pfsum(s1) remove_pfsum(s2) if initial_condition[i]: new_s1 = ms(s1,s2) new_s2 = ms(pairs[s1],pairs[s2]) else: new_s1 = ms(s1,pairs[s2]) new_s2 = ms(pairs[s1],s2) pairs[new_s1] = new_s2 pairs[new_s2] = new_s1 upd_pfsum(new_s1) ans.append(pfsums) for i in ans: print(i) ```
85,812
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1). You're given k subsets A_1, …, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 ≤ i_1 < i_2 < i_3 ≤ k, A_{i_1} ∩ A_{i_2} ∩ A_{i_3} = ∅. In one operation, you can choose one of these k subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation. Let m_i be the minimum number of operations you have to do in order to make the i first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1 and n), they can be either off or on. You have to compute m_i for all 1 ≤ i ≤ n. Input The first line contains two integers n and k (1 ≤ n, k ≤ 3 ⋅ 10^5). The second line contains a binary string of length n, representing the initial state of each lamp (the lamp i is off if s_i = 0, on if s_i = 1). The description of each one of the k subsets follows, in the following format: The first line of the description contains a single integer c (1 ≤ c ≤ n) — the number of elements in the subset. The second line of the description contains c distinct integers x_1, …, x_c (1 ≤ x_i ≤ n) — the elements of the subset. It is guaranteed that: * The intersection of any three subsets is empty; * It's possible to make all lamps be simultaneously on using some operations. Output You must output n lines. The i-th line should contain a single integer m_i — the minimum number of operations required to make the lamps 1 to i be simultaneously on. Examples Input 7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 Output 1 2 3 3 3 3 3 Input 8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 Output 1 1 1 1 1 1 4 4 Input 5 3 00011 3 1 2 3 1 4 3 3 4 5 Output 1 1 1 1 1 Input 19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 Output 0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 Note In the first example: * For i = 1, we can just apply one operation on A_1, the final states will be 1010110; * For i = 2, we can apply operations on A_1 and A_3, the final states will be 1100110; * For i ≥ 3, we can apply operations on A_1, A_2 and A_3, the final states will be 1111111. In the second example: * For i ≤ 6, we can just apply one operation on A_2, the final states will be 11111101; * For i ≥ 7, we can apply operations on A_1, A_3, A_4, A_6, the final states will be 11111111. Submitted Solution: ``` from sys import stdin input = stdin.readline n , k = [int(i) for i in input().split()] pairs = [i + n for i in range(n)] + [i for i in range(n)] initial_condition = list(map(lambda x: x == '1',input().strip())) data = [i for i in range(2*n)] constrain = [-1] * (2*n) h = [0] * (2*n) L = [1] * n + [0] * n dp1 = [-1 for i in range(n)] dp2 = [-1 for i in range(n)] for i in range(k): input() inp = [int(j) for j in input().split()] for s in inp: if dp1[s-1] == -1:dp1[s-1] = i else:dp2[s-1] = i pfsums = 0 ans = [] def remove_pfsum(s1): global pfsums if constrain[s1] == 1: pfsums -= L[s1] elif constrain[pairs[s1]] == 1: pfsums -= L[pairs[s1]] else: pfsums -= min(L[s1],L[pairs[s1]]) def sh(i): while i != data[i]: i = data[i] return i def upd_pfsum(s1): global pfsums if constrain[s1] == 1: pfsums += L[s1] elif constrain[pairs[s1]] == 1: pfsums += L[pairs[s1]] else: pfsums += min(L[s1],L[pairs[s1]]) def ms(i,j): i = sh(i) ; j = sh(j) cons = max(constrain[i],constrain[j]) if h[i] < h[j]: data[i] = j h[i] += 1 L[j] += L[i] constrain[j] = cons return j else: data[j] = i h[j] += 1 L[i] += L[j] constrain[i] = cons return i for i in range(n): if dp1[i] == -1 and dp2[i] == -1: pass elif dp2[i] == -1: s1 = sh(dp1[i]) remove_pfsum(s1) constrain[s1] = 0 if initial_condition[i] else 1 constrain[pairs[s1]] = 1 if initial_condition[i] else 0 upd_pfsum(s1) else: s1 = sh(dp1[i]) ; s2 = sh(dp2[i]) if s1 == s2 or pairs[s1] == s2: pass else: remove_pfsum(s1) remove_pfsum(s2) if initial_condition[i]: new_s1 = ms(s1,s2) new_s2 = ms(pairs[s1],pairs[s2]) else: new_s1 = ms(s1,pairs[s2]) new_s2 = ms(pairs[s1],s2) pairs[new_s1] = new_s2 pairs[new_s2] = new_s1 upd_pfsum(new_s1) ans.append(pfsums) for i in ans: print(i) ``` No
85,813
Provide tags and a correct Python 3 solution for this coding contest problem. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Tags: data structures, divide and conquer, implementation, sortings Correct Solution: ``` def add(sms, cns, n, v, x): while v < n: sms[v] += x cns[v] += 1 v += v & ~(v - 1) def sumtoo(sms, cns, v): sm = 0 cn = 0 while v > 0: sm += sms[v] cn += cns[v] v -= v & ~(v - 1) return sm,cn def go(): n = int(input()) x = list(map(int, input().split())) v = list(map(int, input().split())) sv = sorted(set(v)) sv = {v: k for (k, v) in enumerate(sv,1)} v = [sv[v] for v in v] # mnv, mxv = min(v), max(v) # dfv = mxv - mnv a = sorted(((xx, vv) for xx, vv in zip(x, v)), reverse=True) len_sv = len(sv)+1 sms = [0] * len_sv cns = [0] * len_sv res = 0 sx = 0 for cnt, (xx, vv) in enumerate(a): sm, cn = sumtoo(sms,cns,vv-1) # sm, cn = tree.sum_to(vv - mnv) sm, cn = sx - sm, cnt - cn res += sm - xx * cn add(sms, cns, len_sv, vv, xx) # tree.add(vv - mnv, xx) sx += xx return res print(go()) ```
85,814
Provide tags and a correct Python 3 solution for this coding contest problem. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Tags: data structures, divide and conquer, implementation, sortings Correct Solution: ``` import operator import collections from sys import stdin N = int(input()) pos = list(map(int, stdin.readline().split())) speed = list(map(int, stdin.readline().split())) A = [] for i in range(N): A.append((pos[i], speed[i])) # organized A by position from least to greatest # We want to count, at each x_i, the number of j such that x_j < x_i and # v_j <= x_i dist = {} for i in pos: dist[i] = 0 A.sort(key = operator.itemgetter(0)) # Now we do merge sort on the speeds but with comparing... # if right is chosen over left, then we record [right] += right.pos - left.pos count = [0] def merge_compare(p, r): if p < r: q = (r + p)//2 merge_compare(p, q) merge_compare(q + 1, r) merge(p, q, r) # A is POSITION, SPEED # merging two sorted subsets A[p:q + 1], A[q + 1:r + 1] into a sorted # subset A[p:r + 1] def merge(p, q, r): n_1 = q - p + 1 n_2 = r - q temp = [] L = A[p:q + 1] R = A[q + 1:r + 1] i = 0 j = 0 # calculatin the sum of all the positions in R sum_pos_right = 0 for e, f in R: sum_pos_right += e while i < n_1 and j < n_2: if L[i][1] <= R[j][1]: temp.append(L[i]) count[0] += sum_pos_right - L[i][0]*(n_2 - j) i += 1 else: temp.append(R[j]) sum_pos_right -= R[j][0] j += 1 if i == n_1: temp += R[j:] else: temp += L[i:] A[p:r + 1] = temp merge_compare(0, N - 1) print (count[0]) ```
85,815
Provide tags and a correct Python 3 solution for this coding contest problem. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Tags: data structures, divide and conquer, implementation, sortings Correct Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #from decimal import Decimal #from fractions import Fraction #sys.setrecursionlimit(100000) #INF = float('inf') mod = int(1e9)+7 def update(BIT,v, w): while v <= n: BIT[v] += w v += (v & (-v)) def getvalue(BIT,v): ANS = 0 while v != 0: ANS += BIT[v] v -= (v & (-v)) return ANS def bisect_on_BIT(BIT,x): if x <= 0: return 0 ANS = 0 h = 1 << (n - 1) while h > 0: if ANS + h <= n and BIT[ANS + h] < x: x -= BIT[ANS + h] ANS += h h //= 2 return ANS + 1 n=int(data()) x=mdata() v=mdata() a=[[v[i],x[i]] for i in range(n)] a.sort() s=[0]*(n+1) cnt=[0]*(n+1) pos=dd(int) for i in range(n): pos[a[i][1]]=i+1 for i in range(n): update(s,i+1,a[i][1]) update(cnt,i+1,1) ans=0 x.sort() for i in range(n): ind=pos[x[i]] ans+=getvalue(s,n)-getvalue(s,ind)-(getvalue(cnt,n)-getvalue(cnt,ind))*x[i] update(s,ind,-x[i]) update(cnt,ind,-1) out(ans) ```
85,816
Provide tags and a correct Python 3 solution for this coding contest problem. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Tags: data structures, divide and conquer, implementation, sortings Correct Solution: ``` # -*- coding: utf-8 -*- import sys from collections import Counter 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') # sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 class BIT: def __init__(self, n): n += 1 nv = 1 while nv < n: nv *= 2 self.size = nv self.tree = [0] * nv def sum(self, i): s = 0 i += 1 while i > 0: s += self.tree[i-1] i -= i & -i return s def add(self, i, x): i += 1 while i <= self.size: self.tree[i-1] += x i += i & -i def get(self, l, r=None): if r is None: r = l + 1 res = 0 if r: res += self.sum(r-1) if l: res -= self.sum(l-1) return res def update(self, i, x): self.add(i, x - self.get(i)) def compress(S): zipped, unzipped = {}, {} for i, a in enumerate(sorted(S)): zipped[a] = i unzipped[i] = a return zipped, unzipped N = INT() A = LIST() B = LIST() BA = list(zip(B, A)) BA.sort() zipped, _ = compress(set(A)) bit1 = BIT(N) bit2 = BIT(N) ans = 0 for b, a in BA: sm = bit1.sum(zipped[a]) cnt = bit2.sum(zipped[a]) ans += cnt * a - sm bit1.add(zipped[a], a) bit2.add(zipped[a], 1) print(ans) ```
85,817
Provide tags and a correct Python 3 solution for this coding contest problem. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Tags: data structures, divide and conquer, implementation, sortings Correct Solution: ``` from bisect import bisect_right, bisect_left # instead of AVLTree class BITbisect(): def __init__(self, InputProbNumbers): # 座圧 self.ind_to_co = [-10**18] self.co_to_ind = {} for ind, num in enumerate(sorted(list(set(InputProbNumbers)))): self.ind_to_co.append(num) self.co_to_ind[num] = ind+1 self.max = len(self.co_to_ind) self.data = [0]*(self.max+1) def __str__(self): retList = [] for i in range(1, self.max+1): x = self.ind_to_co[i] if self.count(x): c = self.count(x) for _ in range(c): retList.append(x) return "[" + ", ".join([str(a) for a in retList]) + "]" def __getitem__(self, key): key += 1 s = 0 ind = 0 l = self.max.bit_length() for i in reversed(range(l)): if ind + (1<<i) <= self.max: if s + self.data[ind+(1<<i)] < key: s += self.data[ind+(1<<i)] ind += (1<<i) if ind == self.max or key < 0: raise IndexError("BIT index out of range") return self.ind_to_co[ind+1] def __len__(self): return self._query_sum(self.max) def __contains__(self, num): if not num in self.co_to_ind: return False return self.count(num) > 0 # 0からiまでの区間和 # 左に進んでいく def _query_sum(self, i): s = 0 while i > 0: s += self.data[i] i -= i & -i return s # i番目の要素にxを足す # 上に登っていく def _add(self, i, x): while i <= self.max: self.data[i] += x i += i & -i # 値xを挿入 def push(self, x): if not x in self.co_to_ind: raise KeyError("The pushing number didnt initialized") self._add(self.co_to_ind[x], 1) # 値xを削除 def delete(self, x): if not x in self.co_to_ind: raise KeyError("The deleting number didnt initialized") if self.count(x) <= 0: raise ValueError("The deleting number doesnt exist") self._add(self.co_to_ind[x], -1) # 要素xの個数 def count(self, x): return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1) # 値xを超える最低ind def bisect_right(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_right(self.ind_to_co, x) - 1 return self._query_sum(i) # 値xを下回る最低ind def bisect_left(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_left(self.ind_to_co, x) if i == 1: return 0 return self._query_sum(i-1) # 足す時はi番目に足し、返すのは累積和 class sumBIT(): def __init__(self, N): self.N = N self.bit = [0 for _ in range(self.N+1)] def __str__(self): ret = [] for i in range(1, self.N+1): ret.append(self.__getitem__(i)) return "[" + ", ".join([str(a) for a in ret]) + "]" def __getitem__(self, i): s = 0 while i > 0: s += self.bit[i] i -= i & -i return s def add(self, i, x): while i <= self.N: self.bit[i] += x i += i & -i import sys input = sys.stdin.buffer.readline from operator import itemgetter def main(): N = int(input()) X = list(map(int, input().split())) V = list(map(int, input().split())) XV = [(x, v) for x, v in zip(X, V)] XV.sort() XV.sort(key=itemgetter(1)) co_to_ind1 = {} #co_to_ind2 = {} for i, (x, v) in enumerate(XV): co_to_ind1[x] = i+1 XV.sort() sumbit = sumBIT(N+1) bit = sumBIT(N+1) ans = 0 for x, v in XV: ind1 = co_to_ind1[x] #ind2 = co_to_ind2[v] count = bit[ind1] s = sumbit[ind1] ans += count*x - s bit.add(ind1, 1) sumbit.add(ind1, x) print(ans) if __name__ == "__main__": main() ```
85,818
Provide tags and a correct Python 3 solution for this coding contest problem. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Tags: data structures, divide and conquer, implementation, sortings Correct Solution: ``` import bisect def getsum(tree , i): s = 0 i += 1 while i>0: s += tree[i] i -= i & (-i) return s def updatebit(tree , n , i , v): i+= 1 while i <= n: tree[i] += v i += i & (-i) n = int(input()) x = list(map(int , input().split())) v = list(map(int , input().split())) p = [[x[i] , v[i]] for i in range(len(x))] vs = sorted(list(set(v))) p = sorted(p , key = lambda i : i[0]) l = len(vs) cnt = [0]*(l+1) xs = [0]*(l+1) ans = 0 for pnt in p: pos = bisect.bisect_left(vs , pnt[1]) ans += getsum(cnt , pos) * pnt[0] - getsum(xs , pos) updatebit(cnt , l , pos , 1) updatebit(xs , l , pos , pnt[0]) print(ans) ```
85,819
Provide tags and a correct Python 3 solution for this coding contest problem. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Tags: data structures, divide and conquer, implementation, sortings Correct Solution: ``` import bisect import sys class ft: def __init__(self,n): self.a = [0]*(200000) self.n = n def qry(self,r): ret = 0 while r>=0: ret+=self.a[r] r=(r&(r+1))-1 return ret def upd(self,i,v): while i<self.n: self.a[i]+=v i=(i|(i+1)) input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ n = int(input()) x = list(map(int,input().split())) v = list(map(int,input().split())) f0 = ft(n) f1 = ft(n) a1 = [[] for _ in range(n)] for i in range(n): a1[i].append(x[i]) a1[i].append(v[i]) a1.sort() v.sort() ans = 0 for i in range(n): p = bisect.bisect_left(v,a1[i][1]) ans+=(f0.qry(p)*a1[i][0])-(f1.qry(p)); f0.upd(p,1) f1.upd(p,a1[i][0]) print(ans) ```
85,820
Provide tags and a correct Python 3 solution for this coding contest problem. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Tags: data structures, divide and conquer, implementation, sortings Correct Solution: ``` class SegmentTree(): def __init__(self,N,func,initialRes=0): self.f=func self.N=N self.tree=[0 for _ in range(4*self.N)] self.initialRes=initialRes # for i in range(self.N): # self.tree[self.N+i]=arr[i] # for i in range(self.N-1,0,-1): # self.tree[i]=self.f(self.tree[i<<1],self.tree[i<<1|1]) def updateTreeNode(self,idx,value): #update value at arr[idx] self.tree[idx+self.N]=value idx+=self.N i=idx while i>1: self.tree[i>>1]=self.f(self.tree[i],self.tree[i^1]) i>>=1 def query(self,l,r): #get sum (or whatever function) on interval [l,r] inclusive r+=1 res=self.initialRes l+=self.N r+=self.N while l<r: if l&1: res=self.f(res,self.tree[l]) l+=1 if r&1: r-=1 res=self.f(res,self.tree[r]) l>>=1 r>>=1 return res def getMaxSegTree(arr): return SegmentTree(arr,lambda a,b:max(a,b),initialRes=-float('inf')) def getMinSegTree(arr): return SegmentTree(arr,lambda a,b:min(a,b),initialRes=float('inf')) def getSumSegTree(arr): return SegmentTree(arr,lambda a,b:a+b,initialRes=0) def main(): n=int(input()) xes=readIntArr() ves=readIntArr() #perform coordinate compression on xes. Compressed values shall be the indexes of segment tree xes2=list(sorted(xes)) #xes2[compressed]=x xTox2Map=dict() for i,x in enumerate(xes2): xTox2Map[x]=i #xTox2Map[x]=i arr=[] #[original x, compressed x, v] for i in range(n): arr.append([xes[i],xTox2Map[xes[i]],ves[i]]) arr.sort(key=lambda x:(x[2],x[0])) #sort by v asc, then position asc st=getSumSegTree(n) #for sum of xes stCnts=getSumSegTree(n) #for counts # print(arr) ans=0 for originalX,compressedX,v in arr: smallerSums=st.query(0,compressedX) smallerCounts=stCnts.query(0,compressedX) ans+=originalX*smallerCounts-smallerSums st.updateTreeNode(compressedX,originalX) #update the tree stCnts.updateTreeNode(compressedX,1) # print(ans) print(ans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # import sys # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] inf=float('inf') MOD=10**9+7 main() ```
85,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Submitted Solution: ``` class Points: def __init__(self, x = 0, v = 0): self.x, self.v = x, v class Fenwick_tree: def __init__(self, n = 0): self.n = n self.bit = [0] * (n + 1) def update(self, x, value): while x <= self.n: self.bit[x] += value x += x & -x def get(self, x): sum = 0; while x > 0: sum += self.bit[x]; x -= x & -x return sum # Input: n, x, v = int(input()), list(map(int,input().split())), list(map(int,input().split())) a = [Points(x[i], v[i]) for i in range(n)] a.sort(key = lambda value: value.x) # Compress data: v = [a[i].v for i in range(n)] v.sort() data = {} cnt = 1 for i in range(n): if not data.__contains__(v[i]): data[v[i]] = cnt cnt += 1 # Solve the problem: cnt = Fenwick_tree(n) sum = Fenwick_tree(n) res, i = 0, 0 for i in range(n): a[i].v = data[a[i].v] res += a[i].x * cnt.get(a[i].v) - sum.get(a[i].v) cnt.update(a[i].v, 1) sum.update(a[i].v, a[i].x) print(res) ``` Yes
85,822
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Submitted Solution: ``` import sys input = sys.stdin.readline n=int(input()) X=list(map(int,input().split())) V=list(map(int,input().split())) XV=[(X[i],V[i]) for i in range(n)] #compression_dict_x={a: ind for ind, a in enumerate(sorted(set(X)))} compression_dict_v={a: ind+2 for ind, a in enumerate(sorted(set(V)))} XV=[(XV[i][0], compression_dict_v[XV[i][1]]) for i in range(n)] XV.sort(reverse=True) LEN=len(compression_dict_v)+3 BIT1=[0]*(LEN+1) def update1(v,w): while v<=LEN: BIT1[v]+=w v+=(v&(-v)) def getvalue1(v): ANS=0 while v!=0: ANS+=BIT1[v] v-=(v&(-v)) return ANS BIT2=[0]*(LEN+1) def update2(v,w): while v<=LEN: BIT2[v]+=w v+=(v&(-v)) def getvalue2(v): ANS=0 while v!=0: ANS+=BIT2[v] v-=(v&(-v)) return ANS ANS=0 for x,v in XV: ANS+=(getvalue2(LEN)-getvalue2(v-1))-(getvalue1(LEN)-getvalue1(v-1))*x #print(getvalue2(LEN),getvalue2(v-1),getvalue1(LEN),getvalue1(v-1)) #print(x,v,ANS) update1(v,1) update2(v,x) print(ANS) ``` Yes
85,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Submitted Solution: ``` import math import sys from collections import defaultdict, Counter from itertools import groupby #input = sys.stdin.readline rt = lambda: map(int, input().split()) ri = lambda: int(input()) rl = lambda: list(map(int, input().split())) class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n+1) def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & (-i) return s def add(self, i, val): while i <= self.size: self.tree[i] += val i += i & (-i) def main(): n = ri() x = rl() v = rl() pts = [(xi, vi) for xi, vi in zip(x, v)] pts.sort(key=lambda a: (a[1], a[0])) comprX = {val: i+1 for i, val in enumerate(sorted(x))} bit_x = Bit(n+1) bit_cnt = Bit(n+1) res = 0 for xi, vi in pts: compr = comprX[xi] res += bit_cnt.sum(compr)*xi - bit_x.sum(compr) bit_x.add(compr, xi) bit_cnt.add(compr, 1) print(res) if __name__ == '__main__': main() ``` Yes
85,824
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Submitted Solution: ``` # -*- coding:utf-8 -*- """ created by shuangquan.huang at 2020/3/13 """ import collections import time import os import sys import bisect import heapq from typing import List def solve(N, X, S): si = {} ss = list(sorted(set(S))) for i, s in enumerate(ss): si[s] = i xs = [(x, si[s]) for x, s in zip(X, S)] xs.sort() bitc = [0 for _ in range(N+1)] bitx = [0 for _ in range(N+1)] def add(index, val): while index <= N: bitc[index] += 1 bitx[index] += val index |= index + 1 def get(index): count, xsum = 0, 0 while index >= 0: count += bitc[index] xsum += bitx[index] index = (index & (index + 1)) - 1 return count, xsum ans = 0 for x, s in xs: count, xsum = get(s) ans += count * x - xsum add(s, x) return ans N = int(input()) X = [int(x) for x in input().split()] S = [int(x) for x in input().split()] print(solve(N, X, S)) ``` Yes
85,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Submitted Solution: ``` numberofpoints=int(input()) initcoords=input().split(" ") speeds=input().split(" ") initcoords=list(map(int,initcoords)) speeds=list(map(int,speeds)) def twopoints(coords,velos): firstv=velos[0] secondv=velos[1] firstc=coords[0] secondc=coords[1] if firstv==secondv: return abs(firstc-secondc) elif firstv<=0 and secondv<=0: if firstv<secondv: if firstc<secondc: return abs(firstc-secondc) elif secondc<firstc: return 0 if firstv>secondv: if firstc<secondc: return 0 elif secondc<firstc: return abs(firstc-secondc) elif firstv>0 and secondv>0: if firstv>secondv: if firstc>secondc: return abs(firstc-secondc) elif secondc>firstc: return 0 if firstv<secondv: if firstc>secondc: return 0 elif secondc>firstc: return abs(firstc-secondc) else: return abs(firstc-secondc) lis=[] for first in range(numberofpoints): for second in range(first+1,numberofpoints): tup=(first,second) lis.append(tup) sum=0 for tuple in lis: pone=tuple[0] ptwo=tuple[1] vone=speeds[pone] cone=initcoords[pone] vtwo=speeds[ptwo] ctwo=initcoords[ptwo] a=(vone,vtwo) b=(cone,ctwo) sum+=twopoints(b,a) print(sum) ``` No
85,826
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Submitted Solution: ``` numberofpoints=int(input()) initcoords=input().split(" ") speeds=input().split(" ") initcoords=tuple(map(int,initcoords)) speeds=tuple(map(int,speeds)) def twopoints(coords,velos): firstv=velos[0] secondv=velos[1] firstc=coords[0] secondc=coords[1] dif=abs(firstv-secondv) nextdif=abs((firstc+firstv)-(secondc+secondv)) if dif>nextdif: return 0 else: return dif lis=[] for first in range(numberofpoints): for second in range(first+1,numberofpoints): tup=(first,second) lis.append(tup) sum=0 for tuple in lis: a=(speeds[tuple[0]],speeds[tuple[1]]) b=(initcoords[tuple[0]],initcoords[tuple[1]]) sum+=twopoints(b,a) print(sum) ``` No
85,827
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Submitted Solution: ``` import collections def ff(x, d): res = 0 for i in d.keys(): if i < x: res += 1 else: break return res n = int(input()) x = list(map(int, input().split())) v = list(map(int, input().split())) d = [(x[i], v[i]) for i in range(n)] d.sort(key=lambda x: x[0]) ''' ans = 0 for i in range(1, n): for j in range(i): if d[j][1] <= d[i][1]: ans += d[i][0] - d[j][0] ''' ans = 0 od = collections.OrderedDict() for i in range(n): ind = ff(d[i][1] + 1, od) ans += ind * d[i][0] print(ind * d[i][0]) od[d[i][1]] = i od = collections.OrderedDict() for i in range(n-1, -1, -1): ind = len(od) - ff(d[i][1], od) ans -= ind * d[i][0] print(len(od), ff(d[i][1] - 1, od), -ind * d[i][0]) od[d[i][1]] = i print(ans) ``` No
85,828
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ⋅ v_i. Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0. Your task is to calculate the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of points. The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i is the speed of the i-th point. Output Print one integer — the value ∑_{1 ≤ i < j ≤ n} d(i, j) (the sum of minimum distances over all pairs of points). Examples Input 3 1 3 2 -100 2 3 Output 3 Input 5 2 1 4 3 5 2 2 2 3 4 Output 19 Input 2 2 1 -3 0 Output 0 Submitted Solution: ``` import sys input=sys.stdin.readline def getsum(BITTree,i): s = 0 while i > 0: s += BITTree[i] i -= i & (-i) return(s) def updatebit(BITTree , n , i ,v): while i <= n: BITTree[i] += v i += i & (-i) n=int(input()) x=[int(i) for i in input().split() if i!='\n'] v=[int(i) for i in input().split() if i!='\n'] for i in range(n): v[i]=[v[i],i] v.sort() pos=dict() store,prev=1,v[0][0] for i in range(n): if i>0: if prev==v[i][0]: pos[x[v[i][1]]]=store else: store+=1 pos[x[v[i][1]]]=store else: pos[x[v[i][1]]]=store #print(pos) sort=sorted(pos.keys()) bit=[0]*(n+1) ind=[0]*(n+1) ans,count,diff=0,0,0 length=max(sort) total=0 for i in range(len(sort)): count=getsum(bit,pos[sort[i]]) diff=getsum(ind,pos[sort[i]]) ans+=count*sort[i]-diff updatebit(bit,len(bit)-1,pos[sort[i]],1) updatebit(ind,len(ind)-1,pos[sort[i]],sort[i]) print(int(ans)) ``` No
85,829
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` def oracle(n, start, end): nod = 0 t = n - 1 ii = 0 while start - ii > t*2: if t == 0: nod += 1 break nod += 1 ii += t*2 t -= 1 if t < -10: import sys sys.exit() R = [] for cur in range(nod, n): for v in range(cur+1, n): ii += 1 if start <= ii <= end: R.append(cur + 1) ii += 1 if start <= ii <= end: R.append(v + 1) if ii > end: return R ii += 1 if start <= ii <= end: R.append(1) return R t = int(input()) for _ in range(t): a,b,c = map(int,input().split()) x = oracle(a, b, c) print(*x) ```
85,830
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` t = int(input()) def query(i, n, x): if (x % 2 == 1): return i else: return (i + x // 2) for _ in range(t): n, l, r = map(int, input().split()) i = 1 s = 0 includeOne = False if r == n * (n - 1) + 1: includeOne = True r -= 1 if l == n * (n - 1) + 1: print(1) continue while s + 2 * (n - i) < l: s += 2 * (n - i) i += 1 newS = s allIs = [i] while newS + 2 * (n - i) < r: newS += 2 * (n - i) i += 1 allIs.append(i) allIin = 0 answer = [] i = allIs[0] for x in range(l, r + 1): r = query(i, n, x - s) if r == n: s += 2 * (n - i) i += 1 answer.append(r) if includeOne: answer.append(1) print(*answer) ```
85,831
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` import sys input = sys.stdin.buffer.readline for t in range(int(input())): n,l,r = map(int,input().split()) for i in range(l,min(2*(n-2)+1,r) + 1): print('1' if i & 1 else i//2 + 1 , end = ' ') n_set = n set_idx = 2*(n-2) + 2 while(n_set > 2): ls = l - set_idx + 1 rs = r - set_idx + 1 set_idx += 2*(n_set - 2) set_par = n - n_set + 2 if ls < 2 and rs >= 1:print(n , end = ' ') for i in range(max(2,ls) , min(2*(n_set - 2),rs) + 1): print(set_par + (i-1)//2 if i & 1 else set_par , end = ' ') n_set -= 1 l -= set_idx r -= set_idx if l <= 0 and r>=0:print(n , end = ' ') if r == 1: print(1 , end = ' ') print() ```
85,832
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` for _ in range(int(input())): numbers, LEFTs, RIGHTs = map(int, input().split()) KEYSs = 0 GREATS = 0 for i in range(1, numbers+1): if KEYSs + 2 * (numbers-i) >= LEFTs: GREATS = LEFTs-KEYSs-1 break KEYSs += 2 * (numbers-i) LISTs = [] while len(LISTs) < (RIGHTs-LEFTs+1) + GREATS: for j in range(i+1, numbers+1): LISTs.append(i) LISTs.append(j) i += 1 if i >= numbers: LISTs.append(1) break print (' '.join(list(map(str, LISTs[GREATS:GREATS+RIGHTs-LEFTs+1])))) ```
85,833
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def solve(n,l,r): fir,st = 0,1 while st < n: x = 2*(n-st) if fir+x >= l: break fir += x st += 1 if st == n: return [1] ans = [] for z in range(st+1,n+1): ans.append(st) ans.append(z) st += 1 while len(ans) < r-fir: if st == n: ans.append(1) else: for z in range(st+1,n+1): ans.append(st) ans.append(z) st += 1 return ans[l-fir-1:r-fir] def main(): for _ in range(int(input())): n,l,r = map(int,input().split()) print(*solve(n,l,r)) # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
85,834
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` import sys t=int(sys.stdin.readline()) for _ in range(t): n,l,r=map(int,sys.stdin.readline().split()) prev=0 cur=0 start=1 if l==r and l==n*(n-1)+1: print(1) else: ans=[] while(True): cur+=(n-start)*2 if l<=cur: pos=l-prev total=r-l+1 if(pos%2==1): ans.append(start) total-=1 x=start+pos//2 +1 while(total>0): ans.append(x) if x==n: start+=1 if start==n: start=1 x=start total-=1 if total>0: ans.append(start) total-=1 x+=1 else: x=start+pos//2 while(total>0): ans.append(x) if x==n: start+=1 if start==n: start=1 x=start total-=1 if total>0: ans.append(start) total-=1 x+=1 break prev=cur start+=1 print(*ans) ```
85,835
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def generateForStartVertex(startVertex,n): if startVertex==n: return [1] res=[] other=startVertex+1 while other<=n: res.append(startVertex) res.append(other) other+=1 return res @bootstrap def calc(l,r,startVertex,startIndex,n,res): nextStartIndex=startIndex+2*(n-startVertex) if startVertex==n: nextStartIndex+=1 currIdx=startIndex if l<nextStartIndex: #run calculation for this startVertex, else skip for x in generateForStartVertex(startVertex,n): if l<=currIdx<=r: res.append(x) currIdx+=1 if startVertex+1<=n and r>=nextStartIndex: # need to run next startVertex yield calc(l,r,startVertex+1,nextStartIndex,n,res) yield res def main(): t=int(input()) allans=[] for _ in range(t): n,l,r=readIntArr() res=[] calc(l,r,1,1,n,res) allans.append(res) multiLineArrayOfArraysPrint(allans) return #import sys #input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) import sys input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] inf=float('inf') MOD=10**9+7 main() ```
85,836
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Tags: constructive algorithms, graphs, greedy, implementation Correct Solution: ``` def solve(): n, l, r = [int(i) for i in input().split()] seq = [] i = 1 while l <= r: while l > 2 * n - 2: if l == 3: i = 1 break l -= 2 * n - 2 r -= 2 * n - 2 n -= 1 i += 1 if l%2 == 0: seq.append(l // 2 + i) else: seq.append(i) l += 1 return " ".join(str(i) for i in seq) T = int(input()) for _ in range(T): print(solve()) ```
85,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` def calcStartIndex(vertex,n): i=vertex return 1+2*(i-1)*n-i*i+i def main(): t=int(input()) allans=[] for _ in range(t): n,l,r=readIntArr() startVertex=1 b=n while b>0: while startVertex+b<=n and calcStartIndex(startVertex+b,n)<=l: startVertex+=b b//=2 sv=startVertex idx=calcStartIndex(sv,n) ans=[] adder=1 addTurn=False while idx<=r: #sv,sv+1,sv,sv+2,...sv,n. then sv+=1. if sv==n, then put 1 instead of sv if addTurn: curr=sv+adder adder+=1 else: curr=sv if idx>=l: if sv<n: ans.append(curr) else: ans.append(1) addTurn=not addTurn idx+=1 if curr==n: sv+=1 adder=1 addTurn=False allans.append(ans) multiLineArrayOfArraysPrint(allans) return #import sys #input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) import sys input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] inf=float('inf') MOD=10**9+7 main() ``` Yes
85,838
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` import sys input = sys.stdin.buffer.readline from bisect import bisect_left T = int(input()) for _ in range(T): n, l, r = map(int, input().split()) ls = [ (n-u)*2 for u in range(n+1) ] ls[0] = 1 for i in range(1, n+1): ls[i] += ls[i-1] p = bisect_left(ls, l) sp = [] if p == 0: sp = [0, 0, 0] else: d = l - ls[p-1] sp = [p, p+(d+1)//2, 0 if d%2 else 1] def getp(ls): if ls[0] == 0 or ls == [n-1, n, 1]: return 1 elif ls[2] == 0: return ls[1] elif ls[1] == n: return ls[0]+1 else: return ls[0] def nextp(ls): a, b, c = ls if a == 0: return [1, 2, 0] elif c == 0: return [a, b, 1] elif b < n: return [a, b+1, 0] else: return [a+1, a+2, 0] res = [] for _ in range(r-l+1): #print(sp) res.append(getp(sp)) sp = nextp(sp) print(' '.join(map(str, res))) ``` Yes
85,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` import bisect t=int(input()) for _ in range(t): n,l,r=map(int,input().split()) ans=[] sums=[] tmp=0 for i in range(n-1,0,-1): tmp+=i sums.append(tmp) for i in range(l-1,r): if i%2==0: k=i//2 g=bisect.bisect_right(sums,k) tmp=0 if g==n-1: ans.append(1) else: ans.append(g+1) else: k=(i-1)//2 g=bisect.bisect_right(sums,k) tmp=(g*(2*(n-1)-(g-1)))//2 ans.append(2+g+k-tmp) print(*ans) ``` Yes
85,840
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` #!/usr/bin/env python3 import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n, l, r = map(int, input().split()) num = r - l + 1 init_num = 1 index = 0 for i in range(1, n): init_num = i if l <= (n - i) * 2: index = l l = 0 break else: l -= (n - i) * 2 # Last block if l > 0: print(1) continue ans = [] for i in range(1, n): if i < init_num: continue for j in range((n - i) * 2): if i == init_num and j < index - 1: continue elif j % 2 == 0: ans.append(i) num -= 1 else: ans.append((j+1) // 2 + i) num -= 1 if num == 0: break if num == 0: break if num > 0: ans.append(1) print(*ans) ``` Yes
85,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` from sys import stdin, gettrace from math import sqrt if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() def main(): def solve(): n,l,r = map(int, input().split()) lv = int((2*n+1 - sqrt((2*n-1)**2 -4*(l-1)))/2) lvs = -2*n+2*n*lv-lv*lv+lv lrd = l - lvs - 1 res = [] i = lv j = lv+lrd//2 + 1 for _ in range(l-1, r, 2): res += [i,j] if j < n: j += 1 else: i +=1 j = i+1 if r == n*(n-1)+1: res[r-l] = 1 print(' '.join(map(str, res[:r-l+1]))) q = int(input()) for _ in range(q): solve() if __name__ == "__main__": main() ``` No
85,842
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` import math # решена def task_1343_c(): b = int(input()) array = [int(num) for num in input().split()] maxPositive = 0 minNegative = -10000000000 res = 0 for i in range(b): if array[i] < 0: if i != 0 and array[i - 1] >= 0: res += maxPositive maxPositive = 0 minNegative = max(minNegative, array[i]) else: if i != 0 and array[i - 1] < 0: res += minNegative minNegative = -10000000000 maxPositive = max(maxPositive, array[i]) if minNegative == -10000000000: res += maxPositive else: res += maxPositive + minNegative print(res) # не работает от слова совсем def task_1341_b(): heightLen, doorSize = map(int, input().split()) heights = [int(num) for num in input().split()] perf = [0 for i in range(heightLen)] a = 0 for i in range(heightLen - 1): if i == 0: perf[i] = 0 else: if heights[i - 1] < heights[i] and heights[i] > heights[i + 1]: a += 1 perf[i] = a perf[heightLen - 1] = a max_global = 0 left_global = 0 for i in range(heightLen - doorSize): max_local = perf[i + doorSize - 1] - perf[i] if max_local > max_global: max_global = max_local left_global = i print(max_global + 1, left_global + 1) # решил, чтоб её def task_1340_a(): n = int(input()) array = [int(i) for i in input().split()] for i in range(n - 1): if array[i] < array[i + 1]: if array[i] + 1 != array[i + 1]: print("No") return print("Yes") #решил def task_1339_b(): n = int(input()) array = [int(num) for num in input().split()] array.sort() output = [0 for i in range(0, n)] i = 0 h = 0 j = n - 1 while i <= j: output[h] = array[i] h += 1 i += 1 if h < n: output[h] = array[j] h += 1 j -= 1 for val in reversed(output): print(val, end=' ') # решена def task_1338_a(): n = int(input()) inputArr = [int(num) for num in input().split()] max_sec = 0 for i in range(1, n): local_sec = 0 a = inputArr[i - 1] - inputArr[i] if a <= 0: continue else: b = math.floor(math.log2(a)) local_sec = b + 1 for j in range(b, -1, -1): if a < pow(2, j): continue inputArr[i] += pow(2, j) a -= pow(2, j) if local_sec > max_sec: max_sec = local_sec print(max_sec) def task_1334_d(): n, l ,r = map(int, input().split()) if l == 9998900031: print(1) return res = [] count = 0 start_pos = l for i in range(1, n + 1): count += (n + 1 - i) * 2 if count >= l: for j in range(n - i): res.append(i) res.append(j + i + 1) if count > r: break else: start_pos -= (n + 1 - i) * 2 res.append(1) for i in range(start_pos - 1, start_pos + (r - l)): print(res[i], end=" ") print() a = int(input()) for i in range(a): task_1334_d() ``` No
85,843
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` def genGroup(n): s = [1] for i in range(2, n): s.append(n) s.append(i) s.append(n) return s for tc in range(int(input())): n, beg, end = map(int, input().split()) past = 0 i = 1 while past + 2*i < beg: past += 2*i i += 1 group = i + 1 s = genGroup(group) pos = beg - past - 1 res = [] for i in range(end-beg+1): res.append(s[pos]) pos += 1 if pos == len(s): pos = 0 group += 1 s = genGroup(group) print(*res) ``` No
85,844
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once. Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists. Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r. Input The first line contains the single integer T (1 ≤ T ≤ 100) — the number of test cases. Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n(n - 1) + 1, r - l + 1 ≤ 10^5) — the number of vertices in K_n, and segment of the cycle to print. It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5. Output For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once. Example Input 3 2 1 3 3 3 6 99995 9998900031 9998900031 Output 1 2 1 1 3 2 3 1 Note In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1. In the third test case, it's quite obvious that the cycle should start and end in vertex 1. Submitted Solution: ``` def main(): for _ in inputt(): n, l, r = inputi() i = 1 l -= 1 if l == n * (n - 1): print(1) continue while l >= 2 * (n - i): l -= 2 * (n - i) r -= 2 * (n - i) i += 1 j = i + 1 + l // 2 while l < r: if l % 2: print(j, end = " ") j += 1 if j > n: i += 1 j = i + 1 elif l != n * (n - 1): print(i, end = " ") else: print(1, end = " ") l += 1 print() # region M # region fastio import sys, io, os BUFSIZE = 8192 class FastIO(io.IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = io.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(io.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") def print(*args, **kwargs): for x in args: file.write(str(x)) file.write(kwargs.pop("end", "\n")) sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion # region import inputt = lambda t = 0: range(t) if t else range(int(input())) inputi = lambda: map(int, input().split()) inputl = lambda: list(inputi()) from math import * from heapq import * from bisect import * from itertools import * from functools import reduce, lru_cache from collections import Counter, defaultdict import re, copy, operator, cmath from builtins import * # endregion # region main if __name__ == "__main__": main() # endregion # endregion ``` No
85,845
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Tags: constructive algorithms, dp, flows, graph matchings, greedy, sortings Correct Solution: ``` from typing import List import sys input = sys.stdin.readline import math ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input().strip() return(list(s[:len(s)])) def invr(): return(map(int,input().strip().split())) def solve_hungarian(a: List[List[int]], n: int, m: int): """ Implementation of Hungarian algorithm in n^2 m """ # potentials u = [0] * (n+1) v = [0] * (m+1) # pair row of each col p = [0] * (m+1) # for each col the number of prev col along the augmenting path way = [0] * (m+1) for i in range(1, n+1): p[0] = i j0 = 0 minv = [float('inf')] * (m+1) used = [False] * (m+1) # iterative Kun starts here condition = True while condition: # mark the current col as reachable used[j0] = True i0 = p[j0] delta = float('inf') # determine which col will become reachable after next potential update for j in range(1, m+1): if not used[j]: cur = a[i0][j] - u[i0]-v[j] if cur < minv[j]: minv[j] = cur way[j] = j0 if minv[j] < delta: delta = minv[j] j1 = j # j1 will hold the col with min # way[j1] - the prev col in dfs # update the potential for j in range(0, m+1): if used[j]: # if col j was discovered: u[p[j]] += delta v[j] -= delta else: # not discovered - update min? minv[j] -= delta # j0 becomes the col on which the delta is achieved j0 = j1 # p[j0] == 0 => j0 - a col not in matching condition = p[j0] != 0 # the augmenting path was found - update the mapping condition = True while condition: # j1 is the prev column of j0 in augmenting path j1 = way[j0] p[j0] = p[j1] j0 = j1 condition = j0 != 0 ans = [0] * (n+1) for j in range(1, m+1): ans[p[j]] = j return -v[0], ans def solve(n, k, a, b): A = [[0] * (n+1) for _ in range(n+1) ] for i in range(1, n+1): for j in range(1, k+1): A[i][j] = a[i] + (j-1) * b[i] for j in range(k+1, n+1): A[i][j] = (k-1) * b[i] # turn into a max problem for i, row in enumerate(A): M = max(row) for j in range(n+1): A[i][j] = M - A[i][j] cost, match = solve_hungarian(A, n, n) print(n + (n-k)) role_to_creature = list(zip(match, range(len(match)))) role_to_creature.sort() res = [] for index in range(1, k): res.append(role_to_creature[index][1]) for index in range(k+1, n+1): res.append(role_to_creature[index][1]) res.append(-role_to_creature[index][1]) res.append(role_to_creature[k][1]) print(" ".join(map(str, res))) def from_file(f): return f.readline # with open('test.txt') as f: # input = from_file(f) t = inp() for _ in range(t): n, k = invr() a = [0] b = [0] for _ in range(n): ai, bi = invr() a.append(ai) b.append(bi) solve(n, k, a, b) ```
85,846
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Tags: constructive algorithms, dp, flows, graph matchings, greedy, sortings Correct Solution: ``` from operator import itemgetter import sys int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] def main(): inf = 10 ** 9 for _ in range(II()): n, k = MI() ab = [(a, b, i) for i, (a, b) in enumerate(LLI(n))] dp = [[inf] * n for _ in range(k)] log = [[[] for _ in range(n)] for _ in range(k)] for e in range(n): dp[0][e] = -ab[e][0] ab.sort(key=itemgetter(1)) for a, b, i in ab: for j in range(k - 2, -1, -1): for e in range(n): if i==e:continue pre = dp[j][e] if pre==inf:continue cur = pre + b * (k - 1 - j) - a if cur < dp[j + 1][e]: dp[j + 1][e] = cur log[j+1][e]=log[j][e]+[i] #print(ab) #p2D(dp) #p2D(log) #print() mn=mne=inf for e in range(n): cur=dp[-1][e] if cur<mn: mn=cur mne=e first=log[-1][mne] use=[False]*n use[mne]=True ans=[] for i in first: ans.append(i+1) use[i]=True for i in range(n): if use[i]:continue ans.append(i+1) ans.append(-i-1) ans.append(mne+1) print(len(ans)) print(*ans) main() ```
85,847
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Tags: constructive algorithms, dp, flows, graph matchings, greedy, sortings Correct Solution: ``` def read_int(): return int(input()) def read_ints(): return map(int, input().split(' ')) t = read_int() for case_num in range(t): n, k = read_ints() p = [] for i in range(n): ai, bi = read_ints() p.append((bi, ai, i + 1)) p.sort() dp = [[0 for j in range(k + 1)] for i in range(n + 1)] use = [[False for j in range(k + 1)] for i in range(n + 1)] for i in range(1, n + 1): for j in range(min(i, k) + 1): if i - 1 >= j: dp[i][j] = dp[i - 1][j] + (k - 1) * p[i - 1][0] if j > 0: x = dp[i - 1][j - 1] + (j - 1) * p[i - 1][0] + p[i - 1][1] if x > dp[i][j]: dp[i][j] = x use[i][j] = True used = [] curr = k for i in range(n, 0, -1): if use[i][curr]: used.append(p[i - 1][2]) curr -= 1 used.reverse() seq = used[:-1] st = set(used) for i in range(1, n + 1): if not i in st: seq.append(i) seq.append(-i) seq.append(used[-1]) print(len(seq)) print(' '.join(map(str, seq))) ```
85,848
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Tags: constructive algorithms, dp, flows, graph matchings, greedy, sortings Correct Solution: ``` import sys readline = sys.stdin.readline read = sys.stdin.read ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) prn = lambda x: print(*x, sep='\n') def solve(): n, k = nm() mini = [tuple(nl() + [i+1]) for i in range(n)] mini.sort(key = lambda x: x[1]) # print(mini) dp = [-1]*(k+1) dp[0] = 0 f = [[0]*(k+1) for _ in range(n)] for i in range(n): if dp[k] > 0: dp[k] += (k - 1) * mini[i][1] for j in range(k-1, -1, -1): if dp[j] >= 0: if dp[j+1] < dp[j] + mini[i][0] + j * mini[i][1]: dp[j+1] = dp[j] + mini[i][0] + j * mini[i][1] f[i][j+1] = 1 dp[j] += (k - 1) * mini[i][1] cx = k a = list() b = list() for i in range(n-1, -1, -1): if f[i][cx]: a.append(mini[i][2]) cx -= 1 else: b.append(mini[i][2]) com = list() for x in a[:0:-1]: com.append(x) for x in b: com.append(x) com.append(-x) com.append(a[0]) print(len(com)) print(*com) return T = ni() for _ in range(T): solve() ```
85,849
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Tags: constructive algorithms, dp, flows, graph matchings, greedy, sortings Correct Solution: ``` from sys import stdin, gettrace from heapq import nlargest if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() INF = int(10E10) def main(): def solve(): n, k = map(int, input().split()) mm = [] for i in range(1,n+1): a,b = map(int, input().split()) mm.append((b, a, i)) mm.sort() dp = [[(-1000000, False)] * min(i+1,k+1) for i in range(n+1)] dp[1][0] = (mm[0][0] * (k-1), False) dp[1][1] = (mm[0][1], True) for j,(b,a,_) in enumerate(mm[1:],2): dp[j][0] = (dp[j-1][0][0] + b * (k-1), False) for l in range(1, min(j, k+1)): v1 = dp[j-1][l][0] + b * (k-1) v2 = dp[j-1][l-1][0] + a + b * (l-1) if v1 > v2: dp[j][l] = (v1, False) else: dp[j][l] = (v2, True) if j <= k: dp[j][j] = (dp[j-1][j-1][0] + a + b * (j-1), True) g1 = [] g2 = [] l = k for j in range(n, 0, -1): _, _, i = mm[j-1] if dp[j][l][1]: g1.append(i) l -= 1 else: g2.append(i) g2.append(-i) g1.reverse() res = g1[:k-1] + g2 + g1[k-1:] print(len(res)) print(' '.join(map(str, res))) q = int(input()) for _ in range(q): solve() if __name__ == "__main__": main() ```
85,850
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Submitted Solution: ``` def m(e): return e['m'] def h(e): return e['h'] a = int(input()) for i in range(a): num = [int(x) for x in input().split()] mi = [] for j in range(num[0]): a = [int(x) for x in input().split()] k = {} k['m'] = a[0] k['h'] = a[1] k['i'] = j+1 mi.append(k) mi.sort(key=m,reverse = True) cho = mi nch = mi cho = mi[:num[1]] nch = mi[num[1]:] ksum = 0 klen = 0 k = [] for element in cho[:num[1]-1]: #print(element['i'],end = " ") k.append(element['i']) klen +=1 ksum+=element['m'] ksum+=element['h']*(klen-1) fix = klen #print() #print(nch) if(num[1]!=1): for element in nch: if(element['h']!=0): #print(element['i'],end = " ") #print(-1*element['i'],end = " ") k.append(element['i']) klen +=1 k.append(-1*element['i']) klen +=1 ksum+=(element['h']*fix) k.append(cho[num[1]-1]['i']) klen+=1 ksum+=cho[num[1]-1]['m'] ksum+=cho[num[1]-1]['h']*(klen-1) #print(cho[num[1]-1]['i'],end = " ") mi.sort(key = h) csum = 0 clen = 0 c = [] if(num[1]>1): c.append(mi[0]['i']) clen +=1 csum+=mi[0]['m'] mi = mi[1:] mi.sort(key=m,reverse = True) cho = mi nch = mi cho = mi[:num[1]-1] nch = mi[num[1]-1:] for element in cho[:num[1]-2]: #print(element['i'],end = " ") c.append(element['i']) clen +=1 csum+=element['m'] csum+=element['h']*(clen-1) fix = clen #print() #print(nch) if(num[1]!=1): for element in nch: if(element['h']!=0): #print(element['i'],end = " ") #print(-1*element['i'],end = " ") c.append(element['i']) clen +=1 c.append(-1*element['i']) clen +=1 csum+=(element['h']*fix) c.append(cho[num[1]-2]['i']) clen+=1 csum+=cho[num[1]-2]['m'] csum+=cho[num[1]-2]['h']*(clen-1) #print(cho[num[1]-1]['i'],end = " ") if(csum>ksum): print(clen) for j in c: print(j,end = " ") print() else: print(klen) for j in k: print(j,end = " ") print() """"5 2 3538 43176 24258 77210 92123 70606 44495 37855 65913 67119 8 3 4 -4 2 -2 1 -1 5 8 4 2 -2 5 -5 1 -1 3 """ ``` No
85,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Submitted Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop import math from collections import * from functools import reduce,cmp_to_key,lru_cache import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # import sys # input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip().split()] def st():return str(input().rstrip())[2:-1] def val():return int(input().rstrip()) def li2():return [str(i)[2:-1] for i in input().rstrip().split()] def li3():return [int(i) for i in st()] for _ in range(val()): n,k = li() l = [] for i in range(n):l.append(li() + [i]) l.sort(key = lambda x:(-x[0],x[1])) he = [] ans = [] for i in range(k): for j in range(len(he)): he[j][0] += l[i][1] heappush(he,l[i]) ans.append(l[i][2]) maxans = sum(i[0] for i in he) maxiter = ans[:] for i in range(k): ans.append(-heappop(he)[-1]) currsum = 0 for j in range(len(he)): he[j][0] += l[i][1] currsum += he[j][0] currsum += l[i][0] heappush(he,l[i]) ans.append(l[i][2]) if currsum > maxans: maxans = currsum maxiter = ans[:] for i in range(len(maxiter)): if maxiter[i] < 0: maxiter[i]-=1 else:maxiter[i] += 1 print(len(maxiter)) print(*maxiter) ``` No
85,852
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Submitted Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop import math from collections import * from functools import reduce,cmp_to_key,lru_cache import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # import sys # input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip().split()] def st():return str(input().rstrip())[2:-1] def val():return int(input().rstrip()) def li2():return [str(i)[2:-1] for i in input().rstrip().split()] def li3():return [int(i) for i in st()] for _ in range(val()): n,k = li() l = [] for i in range(n):l.append(li() + [i]) l.sort(key = lambda x:(-x[0],x[1])) he = [] ans = [] for i in range(k): for j in range(len(he)): he[j][0] += l[i][1] heappush(he,l[i]) ans.append(l[i][2]) maxans = sum(i[0] for i in he) maxiter = ans[:] for i in range(k,n): ans.append(-heappop(he)[-1]) currsum = 0 for j in range(len(he)): he[j][0] += l[i][1] currsum += he[j][0] currsum += l[i][0] heappush(he,l[i]) ans.append(l[i][2]) if currsum > maxans: maxans = currsum maxiter = ans[:] for i in range(len(maxiter)): if maxiter[i] < 0: maxiter[i]-=1 else:maxiter[i] += 1 print(len(maxiter)) print(*maxiter) ``` No
85,853
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order. Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once. Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed). Help Polycarp to make up a plan of actions to summon the strongest possible army! Input The first line contains one integer T (1 ≤ T ≤ 75) — the number of test cases. Each test case begins with a line containing two integers n and k (1 ≤ k ≤ n ≤ 75) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 ≤ a_i ≤ 10^5, 0 ≤ b_i ≤ 10^5) — the parameters of the i-th minion. Output For each test case print the optimal sequence of actions as follows: Firstly, print m — the number of actions which Polycarp has to perform (0 ≤ m ≤ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action. If there are multiple optimal sequences, print any of them. Example Input 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 Output 4 2 1 -1 5 1 2 5 5 4 3 2 1 Note Consider the example test. In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10. In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it. In the third test case, Polycarp is able to summon and control all five minions. Submitted Solution: ``` for _ in range(int(input())): n, k = map(int, input().split()) values = [] for i in range(n): a, b = map(int, input().split()) values.append((i + 1, a, b)) if k == 1: best = -1 score = 0 for (i, a, b) in values: if a > score: best = i score = a print(best) else: values = sorted(values, key=lambda x: x[1], reverse=True) keepers = sorted(values[:k], key=lambda x: x[2]) destroyers = sorted([x for x in values[k:] if x[2] > 0], key=lambda x: x[2]) if len(destroyers): turns = [] for i, a, b in keepers[:-1]: turns.append(i) for i, a, b in destroyers: turns.append(i) turns.append(-i) turns.append(keepers[-1][0]) else: turns = [i for i,a, b in keepers] print(len(turns)) print(*turns) ``` No
85,854
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Tags: data structures, greedy, sortings Correct Solution: ``` n,k = map(int,input().split()) a = [] b = [] c = [] for i in range(n): x,y,z = map(int,input().split()) if y == 1 and z != 1: a.append(x) elif y != 1 and z == 1: b.append(x) elif y == 1 and z == 1: c.append(x) else: pass if len(a)+len(c)<k or len(c)+len(b)<k: ans = -1 else: a.sort() b.sort() c.sort() pt1,pt2,pt3 = 0,0,0 move1 = 0 move2 = 0 ans = 0 while True: if len(c) == 0: for i in range(k): ans += a[i] for i in range(k): ans += b[i] break else: if move1 == k and move2 == k: break elif move1<k and move2 == k: if pt1<len(a) and pt3<len(c): if a[pt1]<c[pt3]: ans += a[pt1] pt1 += 1 else: ans += c[pt3] pt3 += 1 elif not(pt1<len(a)) and pt3<len(c): ans += c[pt3] pt3 += 1 else: ans += a[pt1] pt1 += 1 move1 += 1 elif move1 == k and move2<k: if pt2<len(b) and pt3<len(c): if b[pt2]<c[pt3]: ans += b[pt2] pt2 += 1 else: ans += c[pt3] pt3 += 1 elif not(pt2<len(b)) and pt3<len(c): ans += c[pt3] pt3 += 1 else: ans += b[pt2] pt2 += 1 move2 += 1 else: if pt1<len(a) and pt2<len(b) and pt3<len(c): if a[pt1]+b[pt2]<c[pt3]: ans += a[pt1] move1 += 1 ans += b[pt2] move2 += 1 pt1 += 1 pt2 += 1 else: ans += c[pt3] move1 += 1 move2 += 1 pt3 += 1 else: if pt3<len(c): ans += c[pt3] pt3 += 1 move1 += 1 move2 += 1 else: if pt1<len(a): ans += a[pt1] pt1 += 1 move1 += 1 if pt2<len(b): ans += b[pt2] pt2 += 1 move2 += 1 print(ans) ```
85,855
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Tags: data structures, greedy, sortings Correct Solution: ``` n,k=map(int, input().split()) tab=[tuple(map(int,input().split())) for _ in range(n)] both=[tabi[0] for tabi in tab if tabi[1:]==(1,1)] both.sort() alice=[tabi[0] for tabi in tab if tabi[1:]==(1,0)]# tabi[1]==1 and tabi[2]==0] bob=[tabi[0] for tabi in tab if tabi[1:]==(0,1)] alice.sort() bob.sort() ab=[alice[i]+bob[i] for i in range(min(len(alice),len(bob)))] both+=ab both.sort() if len(both)<k: print(-1) else:print(sum(both[:k])) ```
85,856
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Tags: data structures, greedy, sortings Correct Solution: ``` 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)) ```
85,857
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Tags: data structures, greedy, sortings Correct Solution: ``` 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) ```
85,858
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Tags: data structures, greedy, sortings Correct Solution: ``` #import math #from functools import lru_cache #import heapq #from collections import defaultdict #from collections import Counter #from collections import deque #from sys import stdout #from sys import setrecursionlimit #setrecursionlimit(10**7) from sys import stdin input = stdin.readline INF = 10**9 + 7 MAX = 10**7 + 7 MOD = 10**9 + 7 n, k = [int(x) for x in input().strip().split()] c, a, b = [], [], [] for ni in range(n): ti, ai, bi = [int(x) for x in input().strip().split()] if(ai ==1 and bi == 1): c.append(ti) elif(ai == 1): a.append(ti) elif(bi == 1): b.append(ti) c.sort(reverse = True) a.sort(reverse = True) b.sort(reverse = True) alen = len(a) blen = len(b) clen = len(c) m = max(0, k - min(alen, blen)) ans = 0 #print(clen, m) if(m>clen): print('-1') else: for mi in range(m): ans += c.pop() ka = k - m kb = k - m while(ka or kb): ca = (c[-1] if c else float('inf')) da = 0 ap, bp = 0, 0 if(ka): da += (a[-1] if a else float('inf')) ap = 1 if(kb): da += (b[-1] if b else float('inf')) bp = 1 if(da<ca): if(ap): ka -= 1 ans += (a.pop() if a else float('inf')) if(bp): kb -= 1 ans += (b.pop() if b else float('inf')) else: ans += (c.pop() if c else float('inf')) if(ap): ka -= 1 if(bp): kb -= 1 print(ans if ans!=float('inf') else '-1') ```
85,859
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Tags: data structures, greedy, sortings Correct Solution: ``` # stdin = open("testdata.txt") # def input(): # return stdin.readline().strip() def addition(lst,k): lst_alice = [] lst_bob = [] lst_both = [] addition_lst = [] lst.sort() for i in range(len(lst)): if lst[i][1] == 1 and lst[i][2] == 0: lst_alice.append(lst[i]) elif lst[i][1] == 0 and lst[i][2] == 1: lst_bob.append(lst[i]) elif lst[i][1] == 1 and lst[i][2] == 1: lst_both.append(lst[i]) n = min(len(lst_alice),len(lst_bob)) addition_lst = [ [lst_alice[i][j]+lst_bob[i][j] for j in range(3)] for i in range(n)] lst_both.extend(addition_lst) lst_both.sort() if len(lst_both) < k: return -1 ret = 0 for i in range(k): ret += lst_both[i][0] return ret n ,k = map(int,input().split()) lst = [] for _ in range(n): lst.append(list(map(int,input().split()))) print(addition(lst, k)) ```
85,860
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Tags: data structures, greedy, sortings Correct Solution: ``` n, k = tuple(map(int, input().split())) alice = [] bob = [] both = [] for _ in range(n): t, a, b = tuple(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() remain = 0 if k <= len(both): result = sum(both[:k]) else: remain = k - len(both) if remain > len(bob) or remain > len(alice): result = -1 else: result = sum(both) result += sum(alice[:remain]) + sum(bob[:remain]) index = max(0, k - len(both)) lenbob = len(bob) lenalice = len(alice) if result != -1: for i in range(min(k, len(both)) - 1, -1, -1): if index > lenbob - 1 or index > lenalice - 1: break newresult = result - both[i] + alice[index] + bob[index] index += 1 if newresult < result: result = newresult else: break print(result) ```
85,861
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Tags: data structures, greedy, sortings Correct Solution: ``` n,k=list(map(int,input().split())) x=[] y=[] z=[] for i in range(n): t,a,b=list(map(int,input().split())) if a==1 and b==1: z.append(t) elif a==0 and b==1: y.append(t) elif a==1 and b==0: x.append(t) x1=len(x) y1=len(y) z1=len(z) if min(x1,y1)+z1<k: print(-1) else: x.sort() y.sort() s=min(x1,y1) i=0 while i<s: z.append(x[i]+y[i]) i+=1 z.sort() print(sum(z[:k])) ```
85,862
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Submitted Solution: ``` n,k=map(int,input().split()) x=[];y=[];z=[] for i in range(n): t,a,b=map(int,input().split()) if a and b:x.append(t) elif a==1:y.append(t) elif b==1:z.append(t) y.sort();z.sort() for p,q in zip(y,z): x.append(p+q) x.sort() if len(x)<k:print(-1) else:print(sum(x[:k])) ``` Yes
85,863
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Submitted Solution: ``` 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])) ``` Yes
85,864
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Submitted Solution: ``` from collections import deque n, k = list(map(int, input().split())) both_ls = [] a_ls = [] b_ls = [] for i in range(n): t, a, b = list(map(int, input().split())) if a == 1 and b == 0: a_ls.append(t) elif a == 0 and b == 1: b_ls.append(t) elif a == 1 and b == 1: both_ls.append(t) a_ls = sorted(a_ls) b_ls = sorted(b_ls) both_ls = sorted(both_ls) a_ls = deque(a_ls) b_ls = deque(b_ls) both_ls = deque(both_ls) res = 0 broke = False for i in range(k): if len(both_ls)>0 and len(a_ls)>0 and len(b_ls)>0: if both_ls[0] >= (a_ls[0] + b_ls[0]): res += a_ls.popleft() res += b_ls.popleft() else: res += both_ls.popleft() elif len(both_ls)>0: res += both_ls.popleft() elif len(a_ls)>0 and len(b_ls)>0: res += a_ls.popleft() res += b_ls.popleft() else: print(-1) broke = True break if not broke: print(res) ``` Yes
85,865
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Submitted Solution: ``` n, k = [int(x) for x in input().split()] both = [] bob = [] alice = [] for i in range(n): t, a, b = [int(x) for x in input().split()] if(a==1 and b==1): both.append(t) elif(a==1): alice.append(t) elif(b==1): bob.append(t) both.sort() bob.sort() alice.sort() y = max(k-min(len(bob),len(alice)),0) soma_both=0 sa = 0 sb = 0 poss = (len(both)+min(len(alice),len(bob))>=k) if(poss): for i in range(y): soma_both+=both[i] for i in range(max(k-y,0)): sa += alice[i] for i in range(max(k-y,0)): sb += bob[i] ptr1 = k-y ptr2 = k-y resposta = sa+sb+soma_both for i in range(y,len(both)): ptr1-=1 ptr2-=1 if(ptr2==-1 or ptr1==-1): break soma_both+=both[i] sa-=alice[ptr1] sb-=bob[ptr2] if(soma_both+sa+sb>=0): resposta = min(resposta,soma_both+sa+sb) print(resposta) else: print(-1) ``` Yes
85,866
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Submitted Solution: ``` import sys s = sys.stdin.readline().split() n, m, k = int(s[0]), int(s[1]), int(s[2]) elev = False all = [] All = [] Alice = [] Bob = [] Both = [] none = [] z = 1 while n: i = sys.stdin.readline().split() x = 3 i.append(z) while x: i[x - 1] = int(i[x - 1]) x -= 1 all.append(i) if i[1] == i[2]: if i[1] == 0: none.append(i) else: Both.append(i) else: if i[1] == 0: Bob.append(i) else: Alice.append(i) z += 1 n -= 1 Alice.sort(key=lambda x: x[0]) Bob.sort(key=lambda x: x[0]) Both.sort(key=lambda x: x[0]) none.sort(key=lambda x: x[0]) #print('Alice') #print(Alice) #print('Alice') #print('Bob') #print(Bob) #print('Bob') #print('Both') #print(Both) #print('Both') #print('none') #print(none) #print('none') if elev: print('Alice1 = ' + str(len(Alice))) print('Bob1 = ' + str(len(Bob))) print('Both1 = ' + str(len(Both))) print('none1 = ' + str(len(none))) if 2 * k > m: l = 2 * k - m if len(Both) >= l: tresult = Both[:l] Both = Both[l:] All = Alice + Both + Bob + none m = 2 * (m - k) k = k - l else: print(-1) exit() else: tresult = [] if elev: print('Both2 = ' + str(len(Both))) print('tresult = ' + str(len(tresult))) resulta = [] resultb = [] if k > 0: aaa = Alice + Both aaa.sort(key=lambda x: x[0]) if len(aaa) >= k: resulta = aaa[:k] else: print(-1) exit() col_totals1 = [sum(x) for x in zip(*resulta)] xx = col_totals1[2] yy = k - xx #Both = Both[xx:] #Alice = Alice[yy:] #k = k - xx if elev: print('xx, yy = ' + str(xx) + ', ' + str(yy)) print('resulta = ' + str(len(resulta))) print('Both3 = ' + str(len(Both))) print('Alice2 = ' + str(len(Alice))) print('k = ' + str(k)) #if k > 0: bbb = Bob + Both bbb.sort(key=lambda x: x[0]) if len(bbb) >= k: resultb = bbb[:k] else: print(-1) exit() col_totals2 = [sum(x) for x in zip(*resultb)] xxx = col_totals2[1] yyy = k - xxx if elev: print('xxx, xyy = ' + str(xxx) + ', ' + str(yyy)) print('resultb = ' + str(len(resultb))) print('Both4 = ' + str(len(Both))) print('Bob2 = ' + str(len(Bob))) if max(xx, xxx) == xx: resultb = [] Both = Both[xx:] Alice = Alice[yy:] k = k - xx if k > 0: bbb = Bob + Both bbb.sort(key=lambda x: x[0]) if len(bbb) >= k: resultb = bbb[:k] else: print(-1) exit() col_totals2 = [sum(x) for x in zip(*resultb)] xxx = col_totals2[1] yyy = k - xxx Both = Both[xxx:] Bob = Bob[yyy:] else: resulta = [] Both = Both[xxx:] Bob = Bob[yyy:] k = k -xxx if k > 0: aaa = Alice + Both aaa.sort(key=lambda x: x[0]) if len(aaa) >= k: resulta = aaa[:k] else: print(-1) exit() col_totals2 = [sum(x) for x in zip(*resultb)] xx = col_totals2[1] yy = k - xx Both = Both[xx:] Bob = Bob[yy:] if elev: print('xx, yy = ' + str(xx) + ', ' + str(yy)) print('xxx, yyy = ' + str(xxx)+', '+ str(yyy)) print('resultb = ' + str(len(resultb))) print(resultb) print('resulta = ' + str(len(resulta))) print(resulta) print('Bothf = ' + str(len(Both))) print('Bobf = ' + str(len(Bob))) print('Alicf = '+ str(len(Alice))) q = len(resultb) + len(resulta) q = m - q All = Both + Alice + Bob + none All.sort(key=lambda x: x[0]) if elev: print('q = ' + str(q)) print('All = ' + str(len(All))) result = All[:q] result = resulta + resultb + result + tresult result.sort(key=lambda x: x[0]) print(sum(row[0] for row in result)) print(' '.join([str(row[3]) for row in result])) ``` No
85,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Submitted Solution: ``` import sys n, k = input().split() l = [] l1 = [] l2 = [] d = 0 e = 0 m = 0 for i in range(0, int(n)): t, a, b = input().split() if int(a) == 1 and int(b) == 1: l.append(int(t)) if int(a) == 1 and int(b) == 0: l1.append(int(t)) if int(a) == 0 and int(b) == 1: l2.append(int(t)) l.sort() l1.sort() l2.sort() x=len(l) y=len(l1) z=len(l2) if x>=int(k): x=int(k) elif x<int(k) and x!=0: s=int(k)-x else: x=0 m=min(int(y),int(z)) f=int(k)-m h=int(k)//3 v=int(k)%3 g=0 if f<=0: m=int(k) if x==int(k) and (y==0 or z==0): d = sum(l[0:x]) print(d) elif x==int(k) and y!=0 and z!=0 and m==int(k): d = sum(l[0:x]) e = sum(l1[0:m])+sum(l2[0:m]) if v==0: g=sum(l[0:h])+sum(l1[0:h])+sum(l2[0:h]) print(min(d,e,g)) else: print(min(d,e)) elif x==int(k) and y!=0 and z!=0 and m!=int(k): d = sum(l[0:x]) e = sum(l[0:f])+sum(l1[0:m])+sum(l2[0:m]) print(min(d,e)) elif x<int(k) and x!=0 and y!=0 and z!=0 and m==int(k): d = sum(l)+sum(l1[0:s])+sum(l2[0:s]) e = sum(l1[0:m])+sum(l2[0:m]) print(min(d,e)) elif x<int(k) and x!=0 and y!=0 and z!=0 and m!=int(k): if s>y or s>z: print("-1") else: d=sum(l)+sum(l1[0:s])+sum(l2[0:s]) print(d) else: print("-1") ``` No
85,868
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Submitted Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush, nsmallest from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction # sys.setrecursionlimit(pow(10, 6)) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = pow(10, 9) + 7 mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] """ pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppp pppppppp ppppppppppppppppppppp ppppppp ppppppppppppppppppp ppppp pppppppppppppppppppp """ def cmp1(a, b): if not a[1] and b[1]: return 1 if not b[1] and a[1]: return -1 if a[0] <= b[0]: return -1 return 1 def cmp2(a, b): if not a[2] and b[2]: return 1 if not b[2] and a[2]: return -1 if a[0] <= b[0]: return -1 return 1 n, k = sp() mat = [] a, b = 0, 0 for i in range(n): mat.append(l()) if mat[i][1]: a += 1 if mat[i][2]: b += 1 answer = 0 if a < k or b < k: out(-1) exit() if a <= b: mat.sort(key=cmp_to_key(cmp1)) b = 0 for i in range(k): answer += mat[i][0] if mat[i][2]: b += 1 mat[i][2] = 0 mat[i][0] = -1 if b < k: mat.sort(key=cmp_to_key(cmp2)) i = 0 cnt = 0 while cnt < k-b: if mat[i][0] == -1: i += 1 continue cnt += 1 answer += mat[i][0] i += 1 out(answer) exit() mat.sort(key=cmp_to_key(cmp2)) b = 0 for i in range(k): answer += mat[i][0] if mat[i][1]: b += 1 mat[i][1] = 0 mat[i][0] = -1 if b < k: mat.sort(key=cmp_to_key(cmp1)) i = 0 cnt = 0 while cnt < k-b: if mat[i][0] == -1: i += 1 continue cnt += 1 answer += mat[i][0] i += 1 out(answer) ``` No
85,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster. There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not). So they need to choose some books from the given n books in such a way that: * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set; * the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set. Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where: * t_i — the amount of time required for reading the i-th book; * a_i equals 1 if Alice likes the i-th book and 0 otherwise; * b_i equals 1 if Bob likes the i-th book and 0 otherwise. Output If there is no solution, print only one integer -1. Otherwise print one integer T — the minimum total reading time of the suitable set of books. Examples Input 8 4 7 1 1 2 1 1 4 0 1 8 1 1 1 0 1 1 1 1 1 0 1 3 0 0 Output 18 Input 5 2 6 0 0 9 0 0 1 0 1 2 1 1 5 1 0 Output 8 Input 5 3 3 0 0 2 1 0 3 1 0 5 0 1 3 0 1 Output -1 Submitted Solution: ``` 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: i[1] = 1 i[2] = 1 none.append(i) else: i[1] = 0 i[2] = 0 Both.append(i) else: if i[1] == 0: i[1] = 1 i[2] = 0 Bob.append(i) else: i[1] = 0 i[2] = 1 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 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]: 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]) result = All[:q] result = result + tresult + tresult1 + corr + Alice1 + Bob1 #print(sum(row[0] for row in result)) sum = 0 for row in result: sum = sum + row[0] print(sum) if sum == 82207: result.sort(key=lambda x: x[0]) print(All[q-1]) print(All[q]) All = All[q:] print(q) print(result[-1]) print(All[0]) print(' '.join([str(row[3]) for row in result])) ``` No
85,870
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Tags: geometry, math Correct Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') from decimal import Decimal from fractions import Fraction #sys.setrecursionlimit(100000) INF = float('inf') mod = int(1e9)+7 for t in range(int(data())): n=int(data()) a=mdata() if a[0]+a[1]<=a[-1]: print(1,2,n) else: out(-1) ```
85,871
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Tags: geometry, math Correct Solution: ``` import sys from os import path if(path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") def solve(): n = int(input().strip()) a = [int(i) for i in input().rstrip().split()] if(a[-1] - a[0] - a[1]) >= 0 : print(f"1 2 {n}" ) else: print(-1) def main(): tc = int(input().strip()) for case in range(tc): solve() if __name__ == '__main__': main() ```
85,872
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Tags: geometry, math Correct Solution: ``` t=int(input()) while(t): n=int(input()) a=list(map(int,input().split())) if n>2: flag=0 for i in range(len(a)-2): if(a[i]+a[i+1]>a[n-1]): continue else: flag=1 print(i+1,end=" ") print(i+2,end=" ") print(n) break if(flag!=1): print("-1") t=t-1 ```
85,873
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Tags: geometry, math Correct Solution: ``` t = int(input()) for _ in range (t): n = int(input()) A = list(map(int, input().split())) if A[0]+A[1] <= A[-1]: print (1, 2, n) else: print (-1) ```
85,874
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Tags: geometry, math Correct Solution: ``` for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) if(a[0]+a[1]>a[-1]): print("-1") else: print(1,2,n) ```
85,875
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Tags: geometry, math Correct Solution: ``` t=int(input()) for i in range(t): n=int(input()) a=[int(v) for v in input().split()] p=a[0] q=a[1] r=a[-1] if p+q<=r: print(1,2,n) else: print(-1) ```
85,876
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Tags: geometry, math Correct Solution: ``` def solve(n, a): a, b, c = a[0], a[1], a[-1] if a + b > c: print(-1) else: print(1, 2, n) return def main(): inp = lambda: [int(x) for x in input().split()] tc = int(input()) for _ in range(tc): n, a = int(input()), inp() solve(n, a) if __name__ == '__main__': main() ```
85,877
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Tags: geometry, math Correct Solution: ``` for _ in range(int(input())): n=int(input()) lst=list(map(int,input().split())) if lst[0]+lst[1]<=lst[-1]: print(1,2,n) else: print(-1) ```
85,878
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Submitted Solution: ``` for i in range(int(input())): n = int(input()) a = list(map(int,input().split())) print("1 2 "+str(n) if len(a) >= 3 and a[0]+a[1] <= a[n-1] else -1) ``` Yes
85,879
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Submitted Solution: ``` #_______________________________________________________________# def fact(x): if x == 0: return 1 else: return x * fact(x-1) def lower_bound(li, num): #return 0 if all are greater or equal to answer = len(li)-1 start = 0 end = len(li)-1 while(start <= end): middle = (end+start)//2 if li[middle] >= num: answer = middle end = middle - 1 else: start = middle + 1 return answer #index where x is not less than num def upper_bound(li, num): #return n-1 if all are small or equal answer = -1 start = 0 end = len(li)-1 while(start <= end): middle = (end+start)//2 if li[middle] <= num: answer = middle start = middle + 1 else: end = middle - 1 return answer #index where x is not greater than num def abs(x): return x if x >=0 else -x def binary_search(li, val, lb, ub): # ITS A BINARY ans = 0 while(lb <= ub): mid = (lb+ub)//2 #print(mid, li[mid]) if li[mid] > val: ub = mid-1 elif val > li[mid]: lb = mid + 1 else: ans = 1 break return ans def sieve_of_eratosthenes(n): ans = [] arr = [1]*(n+1) arr[0],arr[1], i = 0, 0, 2 while(i*i <= n): if arr[i] == 1: j = i+i while(j <= n): arr[j] = 0 j += i i += 1 for k in range(n): if arr[k] == 1: ans.append(k) return ans def nc2(x): if x == 1: return 0 else: return x*(x-1)//2 def kadane(x): #maximum subarray sum sum_so_far = 0 current_sum = 0 for i in x: current_sum += i if current_sum < 0: current_sum = 0 else: sum_so_far = max(sum_so_far,current_sum) return sum_so_far def mex(li): check = [0]*1001 for i in li: check[i] += 1 for i in range(len(check)): if check[i] == 0: return i def sumdigits(n): ans = 0 while(n!=0): ans += n%10 n //= 10 return ans def product(li): ans = 1 for i in li: ans *= i return ans def maxpower(n,k): cnt = 0 while(n>1): cnt += 1 n //= k return cnt def knapsack(li,sumi,s,n,dp): if s == sumi//2: return 1 elif n==0: return 0 else: if dp[n][s] != -1: return dp[n][s] else: if li[n-1] <= s: dp[n][s] = knapsack(li,sumi,s-li[n-1],n-1,dp) or knapsack(li,sumi,s,n-1,dp) else: dp[n][s] = knapsack(li,sumi,s,n-1,dp) return dp[n][s] def pref(li): pref_sum = [0] for i in li: pref_sum.append(pref_sum[-1] + i) return pref_sum #_______________________________________________________________# ''' ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ▄███████▀▀▀▀▀▀███████▄ ░▐████▀▒▒Aestroix▒▒▀██████ ░███▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▀████ ░▐██▒▒▒▒▒KARMANYA▒▒▒▒▒▒████▌ ________________ ░▐█▌▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████▌ ? ? |▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒| ░░█▒▒▄▀▀▀▀▀▄▒▒▄▀▀▀▀▀▄▒▒▐███▌ ? |___CM ONE DAY___| ░░░▐░░░▄▄░░▌▐░░░▄▄░░▌▒▐███▌ ? ? |▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒| ░▄▀▌░░░▀▀░░▌▐░░░▀▀░░▌▒▀▒█▌ ? ? ░▌▒▀▄░░░░▄▀▒▒▀▄░░░▄▀▒▒▄▀▒▌ ? ░▀▄▐▒▀▀▀▀▒▒▒▒▒▒▀▀▀▒▒▒▒▒▒█ ? ? ░░░▀▌▒▄██▄▄▄▄████▄▒▒▒▒█▀ ? ░░░░▄█████████ ████=========█▒▒▐▌ ░░░▀███▀▀████▀█████▀▒▌ ░░░░░▌▒▒▒▄▒▒▒▄▒▒▒▒▒▒▐ ░░░░░▌▒▒▒▒▀▀▀▒▒▒▒▒▒▒▐ ░░░░░████████████████ ''' from math import * for _ in range(int(input())): #for _ in range(1): n = int(input()) #n,m,sx,sy = map(int,input().split()) #s = input() #s2 = input() #r, g, b, w = map(int,input().split()) a = list(map(int,input().split())) #b = list(map(int,input().split())) #s1 = list(st) #a = [int(x) for x in list(s1)] #b = [int(x) for x in list(s2)] f = 0 ans = lower_bound(a,a[0]+a[1]) if a[ans] < a[0]+a[1]: print(-1) else: print(1,2,ans+1) ``` Yes
85,880
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Submitted Solution: ``` t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) if a[-1]>=a[0]+a[1]: print(1,2,n) else: print(-1) ``` Yes
85,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Submitted Solution: ``` for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) if(arr[0]+arr[1]>arr[n-1]): print("-1") else: print("1 2",n) ``` Yes
85,882
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Submitted Solution: ``` t=int(input()) for _ in range(t): n=int(input()) arr=[int(x) for x in input().split()] li=[] flag = True for i in range(n): if len(li) == 0: li.append(i+1) elif len(li) > 2: break else: #print(arr[i] - arr[li[-1]],li,) if arr[i] - arr[li[-1]] < 2: #print('yes') if flag: li.append(i+1) flag =False else: li.append(i+1) if len(li) == 3: print(*li) else: print("-1") ``` No
85,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Submitted Solution: ``` for p in range(int(input())): n=int(input()) x=[int(x) for x in input().split()] i,j,k=0,1,n-1 a,b,c=x[i],x[j],x[k] if (a+b)<c: print(i+1,j+1,k+1) else: print(-1) ``` No
85,884
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Submitted Solution: ``` def isPossibleTriangle(arr, N): f=0 # loop for all 3 # consecutive triplets for i in range(N - 2): # If triplet satisfies triangle # condition, break if (arr[i] + arr[i + 1] <= arr[i + 2]) and (arr[i+1] + arr[i + 2] <= arr[i]) and (arr[i] + arr[i + 2] <= arr[i + 1]): p = i+1 q=i+2 r=i+3 f=1 break if f==1: print(p, q, r) else: print(-1) t = int(input()) for T in range(t): n = int(input()) l = list(map(int, input().split())) isPossibleTriangle(l, n) ``` No
85,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (3 ≤ n ≤ 5 ⋅ 10^4) — the length of the array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 10^9; a_{i - 1} ≤ a_i) — the array a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print the answer to it in one line. If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. Example Input 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 Output 2 3 6 -1 1 2 3 Note In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer. In the second test case you always can construct a non-degenerate triangle. Submitted Solution: ``` t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) sum1=a[0]+a[1] found=0 for i in range(2,n): if sum1<=a[i]: found=1 break if found!=1: print("-1") else: print(0,1,i) ``` No
85,886
Provide tags and a correct Python 3 solution for this coding contest problem. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Tags: constructive algorithms, implementation Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) arr = [input() for i in range(n)] a = arr[0][1] b = arr[1][0] c = arr[n-2][n-1] d = arr[n-1][n-2] if (a == b): ans = [] if c == a: ans.append([n-1, n]) if d == a: ans.append([n, n-1]) print(len(ans)) for item in ans: print(item[0], item[1]) elif (c == d): ans = [] if c == a: ans.append([1, 2]) if c == b: ans.append([2, 1]) print(len(ans)) for item in ans: print(item[0], item[1]) else: if (a == c) and (b == d): print(2) print(1, 2) print(n, n-1) else: print(2) print(2, 1) print(n, n-1) ```
85,887
Provide tags and a correct Python 3 solution for this coding contest problem. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Tags: constructive algorithms, implementation Correct Solution: ``` for _ in range(int(input())): n=int(input()) arr=[] for i in range(n): temp=list(str(input())) arr.append(temp) change=[] #print(arr) if arr[0][1]==arr[1][0]: if arr[0][1]=="1": if arr[n-2][n-1]!="0": change.append([n-1,n]) if arr[n-1][n-2]!="0": change.append([n,n-1]) else: if arr[n-2][n-1]!="1": change.append([n-1,n]) if arr[n-1][n-2]!="1": change.append([n,n-1]) elif arr[n-2][n-1]==arr[n-1][n-2]: if arr[n-2][n-1]=="1": if arr[0][1]!="0": change.append([1,2]) if arr[1][0]!="0": change.append([2,1]) else: if arr[0][1]!="1": change.append([1,2]) if arr[1][0]!="1": change.append([2,1]) else: if arr[0][1]!="0": change.append([1,2]) if arr[1][0]!="0": change.append([2,1]) if arr[n-1][n-2]!="1": change.append([n,n-1]) if arr[n-2][n-1]!="1": change.append([n-1,n]) print(len(change)) for ar in change: ar=list(map(str,ar)) l=" ".join(ar) print(l) ```
85,888
Provide tags and a correct Python 3 solution for this coding contest problem. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Tags: constructive algorithms, implementation Correct Solution: ``` def ans(a, n): s1 = a[0][1] s2 = a[1][0] f2 = a[n-1][n-2] f1 = a[n-2][n-1] if f1==f2 and s1==s2 and f1!=s1: print(0) #correct elif f1==f2 and f1==s1 and s1==s2: print(2) #change s1 and s2 print('1 2') print('2 1') #correct elif f1==f2: print(1) if s1==f1: #change s1 print('1 2') else: #change s2 print('2 1') elif s1==s2: print(1) if f2==s1: #change f2 print(str(n)+' '+str(n-1)) else: #change f1 print(str(n-1)+' '+str(n)) else: #change s1 print(2) if f1==s1: #change s1 and f2 print('1 2') print(str(n)+' '+str(n-1)) else: #change s1 and f1 print('1 2') print(str(n-1)+' '+str(n)) return m = int(input()) for j in range(m): n = int(input()) a = [] for i in range(n): b = input() a.append(b) ans(a, n) ```
85,889
Provide tags and a correct Python 3 solution for this coding contest problem. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Tags: constructive algorithms, implementation Correct Solution: ``` t = int(input()) for i in range(t): n = int(input()) r = [] for j in range(n): temp = input() r.append(temp) s1, s2 = int(r[0][1]), int(r[1][0]) f1, f2 = int(r[-1][-2]), int(r[-2][-1]) if s1 == s2 and f1 == f2: if s1 != f1: print(0) else: print(2) print(1, 2) print(2, 1) elif s1 == s2 and f1 != f2: if s1 == f1: print(1) print(n, n - 1) else: print(1) print(n - 1, n) elif s1 != s2 and f1 == f2: if f1 == s1: print(1) print(1, 2) else: print(1) print(2, 1) else: if s1 == f1: print(2) print(1, 2) print(n - 1, n) else: print(2) print(2, 1) print(n - 1, n) ```
85,890
Provide tags and a correct Python 3 solution for this coding contest problem. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Tags: constructive algorithms, implementation Correct Solution: ``` def solve(): n = int(input()) start_numbers = set() finish_numbers = set() matrix = list() inversion = list() for _ in range(n): inp = list(input()) matrix.append(inp) start_numbers.add(matrix[0][1]) start_numbers.add(matrix[1][0]) finish_numbers.add(matrix[-1][-2]) finish_numbers.add(matrix[-2][-1]) if len(start_numbers) > 1: if len(finish_numbers) > 1: inversion_number = matrix[1][0] inversion.append((1, 2)) if matrix[-1][-2] == inversion_number: inversion.append((n, n - 1)) else: inversion.append((n - 1, n)) else: if matrix[0][1] == matrix[-1][-2]: inversion.append((1, 2)) else: inversion.append((2, 1)) else: inversion_number = matrix[0][1] if matrix[-1][-2] == inversion_number: inversion.append((n, n - 1)) if matrix[-2][-1] == inversion_number: inversion.append((n - 1, n)) print(len(inversion)) for coords in inversion: print(*coords) def main(): for _ in range(int(input())): solve() if __name__ == '__main__': main() ```
85,891
Provide tags and a correct Python 3 solution for this coding contest problem. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Tags: constructive algorithms, implementation Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = [input() for _ in range(n)] for color in range(2): result = [] if int(a[0][1]) != color: result.append((0, 1)) if int(a[1][0]) != color: result.append((1, 0)) if int(a[n - 1][n - 2]) == color: result.append((n - 1, n - 2)) if int(a[n - 2][n - 1]) == color: result.append((n - 2, n - 1)) if len(result) < 3: print(len(result)) for x, y in result: print(x + 1, y + 1) break ```
85,892
Provide tags and a correct Python 3 solution for this coding contest problem. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Tags: constructive algorithms, implementation Correct Solution: ``` def main(): for _ in range(int(input())): n=int(input()) matx=[] for j in range(n): matx.append([str(x) for x in input()]) x=[int(matx[0][1]),int(matx[1][0])] y=[int(matx[n-1][n-2]),int(matx[n-2][n-1])] if x==[0,0] and y==[1,1 ]: print(0) elif x==[1,1] and y==[0,0]: print(0) elif x==[1,1] and y==[1,1] : print(2) print(1,2) print(2,1) elif x==[0,0] and y==[0,0] : print(2) print(1,2) print(2,1) else: if x==[1,0]: if y==[1,0]: print(2) print(1,2) print(n-1,n) elif y==[0,1]: print(2) print(1,2) print(n,n-1) elif y==[0,0]: print(1) print(2,1) else: print(1) print(1,2) if x == [ 0,1]: if y == [1, 0]: print(2) print(1, 2) print(n, n-1) elif y == [0, 1]: print(2) print(1, 2) print(n - 1, n) elif y == [0, 0]: print(1) print(1,2) else: print(1) print(2,1) if x==[1,1]: if y==[1,0]: print(1) print(n,n-1) elif y==[0,1]: print(1) print(n-1,n) if x==[0,0] : if y==[1,0]: print(1) print(n-1,n) elif y==[0,1]: print(1) print(n,n-1) main() ```
85,893
Provide tags and a correct Python 3 solution for this coding contest problem. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Tags: constructive algorithms, implementation Correct Solution: ``` import sys import math import random from typing import List # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') input = sys.stdin.readline class Cell: def __init__(self, a, row, col): self.a = a self.row = row self.col = col def value(self): return self.a[self.row][self.col] def solve(n, c1, c2, c3, c4) -> List[Cell]: def convert(c1: Cell, c2: Cell, char): ans = [] if c1.value() != char: ans.append(c1) if c2.value() != char: ans.append(c2) return ans # print(n, c1, c2, c3, c4) sol1 = convert(c1, c2, '0') + convert(c3, c4, '1') sol2 = convert(c1, c2, '1') + convert(c3, c4, '0') return sol1 if len(sol1) < len(sol2) else sol2 T = int(input()) for t in range(T): N = int(input()) A = [] for i in range(N): A.append(input()) solution = solve( N, Cell(A, 1, 0), Cell(A, 0, 1), Cell(A, N-1, N-2), Cell(A, N-2, N-1) ) print(len(solution)) for cell in solution: print(cell.row + 1, cell.col + 1) ```
85,894
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Submitted Solution: ``` t = int(input()) for _ in range(t): ans = [] final = [] n = int(input()) for i in range(n): s = input() lol = list(s) ans.append(s) a = ans[0][1] b = ans[1][0] x = ans[n-2][n-1] y = ans[n-1][n-2] #print(a,b,x,y) if(b != '0'): final.append([2,1]) if(a!='0'): final.append([1,2]) if(y!='1'): final.append([n,n-1]) if(x!='1'): final.append([n-1,n]) if(len(final) <=2): print(len(final)) for i in final: print(*i,end ='\n') else: final = [] if(b != '1'): final.append([2,1]) if(a!='1'): final.append([1,2]) if(y!='0'): final.append([n,n-1]) if(x!='0'): final.append([n-1,n]) print(len(final)) for i in final: print(*i,end ='\n') ``` Yes
85,895
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Submitted Solution: ``` import sys from itertools import permutations from itertools import combinations from itertools import combinations_with_replacement #sys.stdin = open('/Users/pranjalkandhari/Desktop/Template/input.txt', 'r') for _ in range( int(input()) ): n = int(input()) a = '' b = '' c = '' d = '' for i in range(0,n): li = list(input()) if(i == 0): a = li[1] if(i == 1): b = li[0] if(i == n-2): c = li[n-1] if(i == n-1): d = li[n-2] comp = [a,b,c,d] a1 = ['0' , '0' , '1' , '1'] a2 = ['1' , '1' , '0' , '0'] n1 = 0 n2 = 0 for i in range(0,4): if(comp[i] != a1[i]): n1 += 1 if(comp[i] != a2[i]): n2+=1 ctr = 0 if(n1<=2): print(n1) if(comp[0] != a1[0]): print('1 2') if(comp[1] != a1[1]): print('2 1') if(comp[2] != a1[2]): print(n-1,n) if(comp[3] != a1[3]): print(n,n-1) else: print(n2) if(comp[0] != a2[0]): print('1 2') if(comp[1] != a2[1]): print('2 1') if(comp[2] != a2[2]): print(n-1,n) if(comp[3] != a2[3]): print(n,n-1) ``` Yes
85,896
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Submitted Solution: ``` t = int(input()) for j in range(t): n = int(input()) a = ['0'] * n for i in range(n): a[i] = str(input()) a[i] = list(a[i]) if a[0][1] == a[1][0]: if a[n - 1][n - 2] == a[n - 2][n - 1]: if a[0][1] == a[n - 1][n - 2]: print(2) if a[0][1] == '0': print(0+1,1+1) print(1+1,0+1) else: print(0+1,1+1) print(1+1,0+1) else: print(0) else: print(1) if a[0][1] =='0': if a[n - 1][n - 2] == '0': print(n - 1+1,n - 2+1) else: print(n - 2+1, n - 1+1) else: if a[n - 1][n - 2] == '1': print(n - 1+1,n - 2+1) else: print(n - 2+1, n - 1+1) else: if a[n - 1][n - 2] == a[n - 2][n - 1]: if a[n - 1][n - 2] == '0': print(1) if a[0][1] == '0': print(0+1,1+1) else: print(1+1, 0+1) else: print(1) if a[0][1] == '1': print(0+1,1+1) else: print(1+1,0+1) else: print(2) if a[0][1] != a[n - 1][n - 2]: print(0+1,1+1) print(n - 1+1,n - 2+1) else: print(0+1,1+1) print(n - 2+1,n - 1+1) ``` Yes
85,897
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Submitted Solution: ``` t = int(input()) for i in range(t): list1 = [] n = int(input()) for j in range(n): list1.append(input()) s_right = list1[0][1] s_down = list1[1][0] f_left = list1[-1][-2] f_up = list1[-2][-1] if s_right==s_down and f_left==f_up: if s_right!=f_left: print(0) else: print(2) print(n-1,' ',n) print(n,' ',n-1) elif s_right!=s_down and f_left==f_up: if s_right==f_left: print(1) print(1,' ',2) elif s_down==f_left: print(1) print(2,' ',1) elif s_right==s_down and f_left!=f_up: if s_right==f_left: print(1) print(n,' ',n-1) elif s_down==f_up: print(1) print(n-1,' ',n) else: print(2) if s_right==f_up: print(1,' ',2) print(n,' ',n-1) elif s_right==f_left: print(1,' ',2) print(n-1,' ',n) ``` Yes
85,898
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it. Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'. For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4) The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n). We can show that there always exists a solution for the given constraints. Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50). Description of the test cases follows. The first line of each test case contains one integers n (3 ≤ n ≤ 200). The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'. The sum of values of n doesn't exceed 200. Output For each test case output on the first line an integer c (0 ≤ c ≤ 2) — the number of inverted cells. In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n). Example Input 3 4 S010 0001 1000 111F 3 S10 101 01F 5 S0101 00000 01111 11111 0001F Output 1 3 4 2 1 2 2 1 0 Note For the first test case, after inverting the cell, we get the following grid: S010 0001 1001 111F Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Sat Sep 19 16:36:57 2020 @author: lakne """ t = int(input()) answers = [] for _ in range(t): n = int(input()) start = [] finish = [] answer = [] grids = [] c = 0 for i in range(n): grid = input() grids.append(grid) start.append(grids[0][1]) start.append(grids[1][0]) finish.append(grids[n-2][n-1]) finish.append(grids[n-1][n-2]) if start[0] != start[1] and finish[0] == finish[1]: c = 1 if start[0] == finish[0]: answer.append([str(2), str(1)]) else: answer.append([str(1), str(2)]) elif start[0] == start[1] and finish[0] == finish[1]: if start[0] == finish[0]: c = 2 answer.append([str(2), str(1)]) answer.append([str(1), str(2)]) else: c = 0 elif start[0] != start[1] and finish[0] != finish[1]: c = 2 if start[0] == finish[0]: answer.append([str(2), str(1)]) answer.append([str(n-1), str(n)]) else: answer.append([str(2), str(1)]) answer.append([str(n), str(n-1)]) elif start[0] == start[1] and finish[0] != finish[1]: c = 1 if start[0] == finish[0]: answer.append([str(n-1), str(n)]) else: answer.append([str(n), str(n-1)]) answers.append([c, answer]) for j in range(t): print(answers[j][0]) for cord in answers[j][1]: print(' '.join(cord)) ``` No
85,899