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. Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles. Input The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Each test case is given in two lines. The first line contains two integers a_1 and b_1 (1 ≤ a_1, b_1 ≤ 100) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers a_2 and b_2 (1 ≤ a_2, b_2 ≤ 100) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). Output Print t answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower). Example Input 3 2 3 3 1 3 2 1 3 3 3 1 3 Output Yes Yes No Submitted Solution: ``` for i in range(int(input())): a,b=sorted(map(int,input().split())) n,m=sorted(map(int,input().split())) if a+n==b==m: print('YES') else: print('NO') ``` Yes
106,300
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles. Input The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Each test case is given in two lines. The first line contains two integers a_1 and b_1 (1 ≤ a_1, b_1 ≤ 100) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers a_2 and b_2 (1 ≤ a_2, b_2 ≤ 100) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). Output Print t answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower). Example Input 3 2 3 3 1 3 2 1 3 3 3 1 3 Output Yes Yes No Submitted Solution: ``` def getLines(num): inputLines = [] for i in range(0,num): line = input() if line: inputLines.append(line) else: break return inputLines def notZeroPow(num,p): return True if num >= 1 and num <= pow(10,p) else False readCount = int(input()) if notZeroPow(readCount,4): lines = getLines(readCount*2) results = [] if len(lines) > 0: for i in range(0,len(lines),2): arr = lines[i].split() arr2 = lines[i+1].split() c = ( int(arr[0]) * int(arr[1]) ) % ( int(arr2[0]) * int(arr2[1]) ) t = int(arr[0]) != int(arr[1]) and int(arr2[0]) != int(arr2[1]) results.append(t and c == 0 ) for e in results: print("Yes" if e else "No") ``` No
106,301
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles. Input The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Each test case is given in two lines. The first line contains two integers a_1 and b_1 (1 ≤ a_1, b_1 ≤ 100) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers a_2 and b_2 (1 ≤ a_2, b_2 ≤ 100) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). Output Print t answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower). Example Input 3 2 3 3 1 3 2 1 3 3 3 1 3 Output Yes Yes No Submitted Solution: ``` from math import sqrt as s for _ in range(int(input())): a,b = map(int,input().split()) c,d = map(int,input().split()) total = a+b+c+d temp = -1 if a==c: total = total-a-c temp=a elif a==d: total = total-a-d temp=a elif b==c: total = total-b-c temp=b elif b==d: total = total-b-d temp=b if total==temp: print('YES') else: print('NO') ``` No
106,302
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles. Input The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Each test case is given in two lines. The first line contains two integers a_1 and b_1 (1 ≤ a_1, b_1 ≤ 100) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers a_2 and b_2 (1 ≤ a_2, b_2 ≤ 100) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). Output Print t answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower). Example Input 3 2 3 3 1 3 2 1 3 3 3 1 3 Output Yes Yes No Submitted Solution: ``` n=int(input()) for x in range(n): l=set() a,b=map(int,input().strip().split()) c,d=map(int,input().strip().split()) s=a+b+c+d for x in range(1,int(s**(1/2)+1)): if x**2==s: print('Yes') break else: print('No') ``` No
106,303
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles. Input The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Each test case is given in two lines. The first line contains two integers a_1 and b_1 (1 ≤ a_1, b_1 ≤ 100) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers a_2 and b_2 (1 ≤ a_2, b_2 ≤ 100) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). Output Print t answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower). Example Input 3 2 3 3 1 3 2 1 3 3 3 1 3 Output Yes Yes No Submitted Solution: ``` x =int(input()) while(x>0): l1= input() l1.split(' ') l1a=[] l2a=[] for i in l1: if(i!=' '): l1a.append(int(i)) if(l1a[0]<=l1a[1]): min1=l1a[0] l1other=l1a[1] else: min1 = l1a[1] l1other=l1a[0] l2 = input() l2.split(' ') for i in l2: if(i!=' '): l2a.append(int(i)) if(l2a[0]<=l2a[1]): min1=l2a[0] l2other=l2a[1] else: min2 = l2a[1] l2other=l2a[0] summin=min1+min2 if(summin==l1other & l2other==summin): print("Yes\n") else: print("No\n") x-=1 ``` No
106,304
Provide tags and a correct Python 3 solution for this coding contest problem. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Tags: constructive algorithms, greedy, implementation Correct Solution: ``` import math import sys t = int(input()) result = [] for cs in range(t): n, k = map(int, input().split()) a = [[0] * n for _ in range(n)] result.append('0' if k % n == 0 else '2') for i in range(n): cur = 0 while cur < n and k > 0: a[cur][(i + cur) % n] = 1 k -= 1 cur += 1 for i in range(n): result.append(''.join(map(str, a[i]))) print('\n'.join(result)) ```
106,305
Provide tags and a correct Python 3 solution for this coding contest problem. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Tags: constructive algorithms, greedy, implementation Correct Solution: ``` t = int(input()) for test in range(t): n,k = [int(i) for i in input().split()] tab = [["0" for c in range(n)] for r in range(n)] row = 0 col = 0 while k>0: tab[row][col] = "1" row = (row+1)%n col += 1 if col==n: col = 0 row = (row+1)%n k -= 1 if col==0: print(0) else: print(2) for row in range(n): print(''.join(tab[row])) ```
106,306
Provide tags and a correct Python 3 solution for this coding contest problem. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Tags: constructive algorithms, greedy, implementation Correct Solution: ``` import sys input = lambda:sys.stdin.readline().strip() t = int(input()) while t: t-=1 n,k = map(int,input().split()) if k%n==0: print(0) else: print(2) ans = [[0]*n for _ in range(n)] p = 0 q = 0 while k: ans[p][q] = 1 k-=1 p+=1 q+=1 q%=n if p==n: p=0 q+=1 q%=n for i in range(n): print(''.join(map(str,ans[i]))) ```
106,307
Provide tags and a correct Python 3 solution for this coding contest problem. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Tags: constructive algorithms, greedy, implementation Correct Solution: ``` for z in range(int(input())): n,k = list(map(int,input().split())) arr = [[0 for i in range(n)] for i in range(n)] c = 0 s = [0,0] while(k!=0): # print(s) arr[s[0]][s[1]]=1 s[0] = (s[0]+1)%n s[1] = (s[1]+1)%n c+=1 if(c==n): c=0 s[1]=(s[1]+1)%n k-=1 min_c,max_c = n,0 for i in range(n): col = 0 for j in range(n): if(arr[j][i]): col+=1 if col<min_c: min_c = col if col>max_c: max_c =col min_r,max_r = n,0 for i in range(n): row = 0 for j in range(n): if(arr[i][j]): row+=1 if row<min_r: min_r = row if row>max_r: max_r =row print((max_c-min_c)**2 + (max_r-min_r)**2) for i in arr: for j in i: print(j,end="") print() ```
106,308
Provide tags and a correct Python 3 solution for this coding contest problem. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Tags: constructive algorithms, greedy, implementation Correct Solution: ``` input=__import__('sys').stdin.readline for _ in range(int(input())): n,k=map(int,input().split()) print(2if k%n else 0) ans=[['0']*n for i in range(n)] x=y=0 while k:k-=1;ans[x][y]='1';y=(y+1+int(x==n-1))%n;x=(x+1)%n for i in ans:print(''.join(i)) ```
106,309
Provide tags and a correct Python 3 solution for this coding contest problem. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Tags: constructive algorithms, greedy, implementation Correct Solution: ``` t = int(input()) while t!=0: n,k=map(int,input().split()) list1=[[0 for i in range(n)] for j in range(n)] i,j=0,0 ans=0 if k%n==0: ans=0 else: ans=2 for _ in range(k): list1[i][j]=1 i+=1 j=(j+1)%n if i==n: i=0 j=(j+1)%n print(ans) for i in list1: for j in i: print(j,end='') print() t-=1 ```
106,310
Provide tags and a correct Python 3 solution for this coding contest problem. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Tags: constructive algorithms, greedy, implementation Correct Solution: ``` import sys import math strInp = lambda : input().strip().split() intInp = lambda : list(map(int,strInp())) for t in range(int(input())): n , k = intInp() if k == 0: print(0) for i in range(n): for j in range(n): print('0', end="") print() else: if k%n == 0: print(0) else: print(2) ans = [] for i in range(n): ans.append(['0'] * n) i = 0 #rows j = 0 #columns circle = 0 while k > 0: ans[i][j] = '1' i += 1 j += 1 circle += 1 if i == n: i = 0 if j == n: j = 0 if circle % n == 0: j = circle//n k -= 1 for i in range(n): for j in range(n): print(ans[i][j], end="") print() ```
106,311
Provide tags and a correct Python 3 solution for this coding contest problem. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Tags: constructive algorithms, greedy, implementation Correct Solution: ``` for _ in range(int(input())): n,k=map(int,input().split()) a=[["0" for i in range(n+1)] for j in range(n+1)] r=1 c=1 for i in range(k): a[r][c]="1" r+=1 c+=1 if c==n+1: c=1 if r==n+1: r=1 c=(i+1)//n +1 if k%n: print(2) else: print(0) for i in a[1:]: print("".join(i[1:])) ```
106,312
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Submitted Solution: ``` ''' import itertools def brute(n, k): l = [] for i in range(n): for j in range(n): l.append((i, j)) combos = itertools.combinations(l, k) m = 100000 for combo in combos: rd, cd = {-1 : 0}, {-1 : 0} for sq in combo: if sq[0] in rd: rd[sq[0]] += 1 else: rd[sq[0]] = 1 if sq[1] in cd: cd[sq[1]] += 1 else: cd[sq[1]] = 1 if len(rd) == n + 1: del rd[-1] if len(cd) == n + 1: del cd[-1] fa = (max(rd.values()) - min(rd.values())) ** 2 + (max(cd.values()) - min(cd.values())) ** 2 #print(fa, combo, rd, cd) m = min(m, fa) return m ''' def main(): t = int(input()) for _ in range(t): n, k = map(int, input().split()) if k <= n: if k == n or k == 0: print(0) else: print(2) for ii in range(n): s = "" for jj in range(n): if ii == jj and k > 0: s += "1" k -= 1 else: s += "0" print(s) continue if k % n == 0: print(0) diags = k // n else: print(2) diags = ((k // n) + 1) l = [n - 1] for x in range(diags - 1): l.append(x) l.append(n + x) setl = set(l) printl = [] have = 0 for i in range(n): s = [] for j in range(n): if (i + j) in setl: s.append("1") have += 1 else: s.append("0") printl.append(s) have -= k current_diag = l.pop() cr = n - 1 cc = current_diag - n + 1 while have > 0: have -= 1 printl[cr][cc] = "0" cr -= 1 cc += 1 if cc >= n: break current_diag = l.pop() cr = current_diag cc = 0 while have > 0: have -= 1 printl[cr][cc] = "0" cr -= 1 cc += 1 if cr < 0: break for row in printl: print("".join(row)) main() ``` Yes
106,313
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Submitted Solution: ``` import sys import math from collections import defaultdict,Counter # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP2/output.txt",'w') # sys.stdin=open("CP2/input.txt",'r') # m=pow(10,9)+7 t=int(input()) for i in range(t): n,k=map(int,input().split()) d=k//n if k%n==0: print(0) else: print(2) # l=[[0]*n for j in range(n)] rem=k%n for j in range(n): k1=d if rem: rem-=1 k1+=1 s1='1'*min(k1,n-j) s2='' if n-j>k1: s1+='0'*(n-j-k1) s2+='0'*j else: s2+='1'*(k1-n+j) s2+='0'*(n-k1) print(s2+s1) ``` Yes
106,314
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Submitted Solution: ``` from sys import stdin input = stdin.readline def main(): test = int(input()) for _ in range(test): # n = int(input()) n, k = [int(i) for i in input().split(" ")] # x,y,n = [int(i) for i in input().split(" ")] # a, b, n, m = [int(i) for i in input().split(" ")] # # l = list(input().strip()) # l = [int(i) for i in input().split(" ")] # # for i in l: # print(i, end=' ') # print() matrix = [[0 for i in range(n)] for i in range(n)] col = k // n row = (k % n) ans = 0 if row != 0: ans = 2 for i in range(n): temp = col if row > 0: row -= 1 temp += 1 j = i while temp > 0: matrix[i][j] = 1 j += 1 temp -= 1 if j == n: j = 0 print(ans) for i in matrix: for j in i: print(j, end='') print() main() ``` Yes
106,315
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Submitted Solution: ``` for _ in range(int(input())): n,k = map(int,input().split()) if k%n==0: print('0') else: print('2') a = [["0" for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): if k == 0: break a[j][(i+j)%n]= "1" k-=1 if k==0: break for i in range(n): print("".join(a[i])) ``` Yes
106,316
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Submitted Solution: ``` t = int(input()) while t!=0: n,k = map(int,input().split()) list1 = [] ans=0 for i in range(n): temp = [] for j in range(n): if k>0: if j==i: temp.append(1) k-=1 else: temp.append(0) else: temp.append(0) list1.append(temp) if k<=0: if k==0: print(0) else: print(2) for i in range(n): for j in range(n): print(list1[i][j], end="") print() else: p = k//n q = k%n if q==0: print(0) else: print(2) for i in range(n): count = p for j in range(n): if count>0 and list1[i][j]==0: list1[i][j]=1 count-=1 for i in range(n): for j in range(n): if q>0 and list1[i][j]==0: list1[i][j]=1 q-=1 if q<=0: break if q<=0: break for i in range(n): for j in range(n): print(list1[i][j],end="") print() t-=1 ``` No
106,317
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). 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 import sys input = sys.stdin.readline M = mod = 998244353 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('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('\n')] for _ in range(val()): n, k = li() l = [[0 for i in range(n)] for j in range(n)] up = [0,1] down = [0,0] par = 1 rows = [0]*n cols = [0]*n # print('K : ',k) while k: if par: i,j = down[0],down[1] else: i,j = up[0],up[1] while i < n and j < n and k: k -= 1 l[i][j] = 1 rows[i] += 1 cols[j] += 1 i += 1 j += 1 # print('K : ',k) # for i in l:print(*i) if par: down[0] += 1 else: up[1] += 1 par = 1 - par ans = 0 ans = (max(rows) - min(rows))**2 + (max(cols) - min(cols)) ** 2 print(ans) for i in l:print(*i,sep = '') ``` No
106,318
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Submitted Solution: ``` ''' import itertools def brute(n, k): l = [] for i in range(n): for j in range(n): l.append((i, j)) combos = itertools.combinations(l, k) m = 100000 for combo in combos: rd, cd = {-1 : 0}, {-1 : 0} for sq in combo: if sq[0] in rd: rd[sq[0]] += 1 else: rd[sq[0]] = 1 if sq[1] in cd: cd[sq[1]] += 1 else: cd[sq[1]] = 1 if len(rd) == n + 1: del rd[-1] if len(cd) == n + 1: del cd[-1] fa = (max(rd.values()) - min(rd.values())) ** 2 + (max(cd.values()) - min(cd.values())) ** 2 #print(fa, combo, rd, cd) m = min(m, fa) return m ''' def main(): t = int(input()) for _ in range(t): n, k = map(int, input().split()) if k <= n: if k == n or k == 0: print(0) else: print(1) for ii in range(n): s = "" for jj in range(n): if ii == jj and k > 0: s += "1" k -= 1 else: s += "0" print(s) continue if k % n == 0: print(0) diags = n else: print(2) diags = ((k // n) + 1) l = [n - 1] for x in range(diags - 1): l.append(x) l.append(n + x) setl = set(l) printl = [] have = 0 for i in range(n): s = [] for j in range(n): if (i + j) in setl: s.append("1") have += 1 else: s.append("0") printl.append(s) have -= k current_diag = l.pop() cr = n - 1 cc = current_diag - n + 1 while have > 0: have -= 1 printl[cr][cc] = "0" cr -= 1 cc += 1 if cc >= n: break current_diag = l.pop() cr = current_diag cc = 0 while have > 0: have -= 1 printl[cr][cc] = "0" cr -= 1 cc += 1 if cr < 0: break for row in printl: print("".join(row)) main() ``` No
106,319
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A). Submitted Solution: ``` import math from sys import stdin from collections import Counter,defaultdict,deque input=stdin.readline mod=pow(10,9)+7 def solve(): n,k=map(int,input().split()) if(k==0): print(0) for i in range(n): for j in range(n): print(0,end=" ") print() elif(k==(n*n)): print(0) for i in range(n): for j in range(n): print(1,end=" ") print() elif(k==n): print(0) for i in range(n): for j in range(n): if((i+j)==(n-1)): print(1,end=" ") else: print(0,end=" ") print() elif(k<n): print(2) for i in range(n): for j in range(n): if((i+j)==(n-1) and k>0): print(1,end=" ") k=k-1 else: print(0,end=" ") print() else: l1=[[0 for i in range(n)] for j in range(n)] c=0 x1=math.ceil(k/n) x2=math.floor(k/n) c=2*((x1-x2)*(x1-x2)) print(c) n1=n for i in range(n): x1=math.ceil(k/n1) k=k-x1 for j in range(n): if(x1>0): c=i x1=x1-1 l1[c%n][j]=1 c=c+1 n1=n1-1 for i in range(n): print(*l1[i]) for _ in range(int(input())): solve() ``` No
106,320
Provide tags and a correct Python 3 solution for this coding contest problem. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Tags: dp, greedy, sortings, two pointers Correct Solution: ``` import math,sys,bisect,heapq,os from collections import defaultdict,Counter,deque from itertools import groupby,accumulate from functools import lru_cache #sys.setrecursionlimit(200000000) pr = lambda x: x def input(): return sys.stdin.readline().rstrip('\r\n') #input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ aj = lambda: list(map(int, input().split())) def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) def solve(): n,d,m = aj() A = aj() P = [] M = [] for i in A: if i > m: P.append(i) else: M.append(i) P.sort(reverse = True) M.sort(reverse = True) if not P: print(sum(M)) return ans = sum(M) + P[0] usedp =1 usedm =len(M) tot = ans while 0<= usedp <= len(P) and 0 <= usedm <= len(M): rem = n - (usedp+usedm+1) #if we used 1 extra if rem - usedp*d >= 0: usedp += 1 if usedp > len(P): break tot += P[usedp - 1] else: if usedm == 0: break tot -= M[usedm-1] usedm -=1 ans= max(ans,tot) print(ans) try: #os.system("online_judge.py") sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') from aj import * except: pass solve() ```
106,321
Provide tags and a correct Python 3 solution for this coding contest problem. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Tags: dp, greedy, sortings, two pointers Correct Solution: ``` N, D, M = map(int, input().split()) A = sorted(map(int, input().split()), reverse=True) L = [a for a in A if a>M] S = [a for a in A if a<=M] cum_S = [0] c = 0 for s in S: c += s cum_S.append(c) d = N-1 ans = max(A) if len(L) == 0: print(sum(S)) exit() cum_L = 0 for n, l in enumerate(L, 1): cum_L += l if d < 0: break need = (n-1)*D if not len(L) - n <= need: if len(L) - n <= need + D: need = len(L) - n else: d -= D+1 continue n_s = need - (len(L) - n) #print(n_s) an = cum_S[max(0, len(S)-n_s)] + cum_L #print(n, an, need) ans = max(ans, an) d -= D+1 print(ans) ```
106,322
Provide tags and a correct Python 3 solution for this coding contest problem. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Tags: dp, greedy, sortings, two pointers Correct Solution: ``` from sys import stdin import sys n,d,m = map(int,stdin.readline().split()) a = list(map(int,stdin.readline().split())) a.sort() a.reverse() over = [0] below = [0] nuse = 0 for i in range(n): if a[i] > m: over.append(over[-1] + a[i]) else: below.append(below[-1] + a[i]) ans = 0 #ans = over[min( len(over)-1 , (n+d) // (d+1) )] if len(over) == 1: print (below[-1]) sys.exit() #left for l in range(n+1): r = n - l if l > len(below)-1: break if r < len(over)-1 or (len(over)-1) * (d+1) < r: continue ans = max(ans , below[l] + over[(r+d)//(d+1)]) print (ans) ```
106,323
Provide tags and a correct Python 3 solution for this coding contest problem. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Tags: dp, greedy, sortings, two pointers Correct Solution: ``` import sys import math,bisect from collections import defaultdict from itertools import groupby,accumulate from heapq import heapify,heappop,heappush from collections import deque,Counter,OrderedDict #input = iter(sys.stdin.buffer.read().decode().splitlines())._next_ def neo(): return map(int,input().split()) def Neo(): return list(map(int,input().split())) n,d,m = neo() A = Neo() G,L = [],[] for i in A: if i > m: G.append(i) else: L.append(i) G.sort(reverse = True) L.sort() Gpf = list(accumulate(G)) Lpf = list(accumulate(L)) Gpf = [0]+Gpf Lpf = [0]+Lpf Ans = [] for i in range(len(Gpf)): days = (i-1)*(d+1)+1 if days <= n: t = Gpf[i] rd = n - days t += Lpf[-1] - Lpf[max(0,len(Lpf)-rd-1)] Ans.append(t) print(max(Ans)) ```
106,324
Provide tags and a correct Python 3 solution for this coding contest problem. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Tags: dp, greedy, sortings, two pointers Correct Solution: ``` n,d,m=map(int,input().split()) a=list(map(int,input().split())) e,f=[i for i in a if i<=m],[i for i in a if i>m] e.sort(reverse=True) f.sort(reverse=True) c=len(e) if c==n: print(sum(a)) exit() l=1 r=min((n-1)//(d+1)+1,len(f)) #k's range #e,f 's sum ans=sum(e) nowe,nowf=0,0 #print(l,r) #print(n-(1+(l-1)*(d+1)),l) #print(e,f) #print(l,r) #print(e) #print(f) for i in range(l,r+1): if i==l: nowe=sum(e[:n-(1+(l-1)*(d+1))]) nowf=sum(f[:l]) ans=max(nowe+nowf,ans) continue nowe-=sum(e[n-(1+(i-1)*(d+1)):n-(1+(i-1-1)*(d+1))]) nowf+=f[i-1] ans=max(nowe+nowf,ans) print(ans) ```
106,325
Provide tags and a correct Python 3 solution for this coding contest problem. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Tags: dp, greedy, sortings, two pointers Correct Solution: ``` n, d, m = map(int, input().split()) a = list(map(int, input().split())) small, big = [], [] for i in a: if i > m: big.append(i) else: small.append(i) small.sort(reverse=True) big.sort(reverse=True) res = 0 if len(small) == 0: cnt = int((n + d) / (d + 1)) for i in range(cnt): res += big[i] elif len(big) == 0: res = 0 for i in range(n): res += small[i] else: sum = [small[0]] for i in range(1, len(small)): sum.append(sum[i - 1] + small[i]) tot = 0 for i in range(len(big)): tot += big[i] rem = min(n - (i * (d + 1) + 1), len(sum)) if rem == 0: res = max(res, tot) elif rem > 0: res = max(res, tot + sum[rem - 1]) else: break print(res) ```
106,326
Provide tags and a correct Python 3 solution for this coding contest problem. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Tags: dp, greedy, sortings, two pointers Correct Solution: ``` # TestCases # 5 2 11 # 8 10 15 23 5 # # 48 # 20 2 16 # 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 # # 195 from math import ceil import sys read = lambda: sys.stdin.readline().rstrip("\r\n") def maxFun(): n, d, m = map(int, read().split()) nums = list(map(int, read().split())) nums.sort(reverse = True) smaller = list() larger = list() for i in nums: if i <= m: smaller.append(i) else: larger.append(i) large_len = len(larger) smaller = smaller + [0] * (n - len(smaller)) larger = larger + [0] * (n - len(larger)) large_suff = [0] * (n+1) small_pre = [0] * (n+1) for i in range(1, n+1): small_pre[i] = small_pre[i - 1] + smaller[i-1] large_suff[i] = large_suff[i - 1] + larger[i-1] # print(small_pre) # print(large_suff) ans = small_pre[-1] for j in range(1, large_len + 1): pos = (j - 1) * (d + 1) + 1 if pos > n: break ans = max(ans, large_suff[j] + small_pre[n - pos]) print(ans) if __name__ == "__main__": maxFun() ```
106,327
Provide tags and a correct Python 3 solution for this coding contest problem. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Tags: dp, greedy, sortings, two pointers Correct Solution: ``` def solve(n, d, m, a): a.sort() small = sorted(x for x in a if x <= m) scs = [0] for x in small: scs.append(scs[-1] + x) sol = scs[-1] bn = n - len(small) take, r, sbig, possible = 1, n-1, 0, True while possible: skip = d*(take-1) if a[r] > m and skip + take <= n: sbig += a[r] skip = max(skip - (bn - take), 0) ssmall = scs[-1] - scs[skip] if skip < len(scs) else 0 sol = max(sol, sbig + ssmall) r -= 1 take += 1 else: possible = False return sol # 1 2 2 2 4 5 5 6 7 8 13 16 16 16 16 16 17 18 20 21 n, d, m = map(int, input().split()) a = list(map(int, input().split())) print(solve(n, d, m, a)) ```
106,328
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Submitted Solution: ``` def solve(): n, d, m = map(int, input().split());a = list(map(int, input().split()));f = list();g = list() for x in a: if x > m:f.append(x) else:g.append(x) f.sort(reverse=True);g.sort(reverse=True);ng = len(g);a = [0] * (ng + 1) for i in range(ng):a[i+1] = a[i] + g[i] ans = a[ng];cur = 0 for i in range(len(f)): if i + 1 + i * d > n: break cur += f[i];v = n - i * d - i - 1 if v > ng: v = ng if v < 0: v = 0 if ans < cur + a[v]:ans = cur + a[v] print(ans) return solve() ``` Yes
106,329
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Submitted Solution: ``` ''' Author: nuoyanli Date: 2020-08-12 22:26:14 LastEditTime: 2020-08-13 00:22:36 Author's blog: https://blog.nuoyanli.com/ Description: Plum blossom from the bitter cold! ''' import sys readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) n,d,m =nm() a = nl() num = 0 for i in range(n): num+=(a[i]<=m) a.sort() a.insert(0,0) su = [] su.append(0) for i in range(1,n+1): su.append(su[i-1]+ a[i]) div ,ans = n-num,0 d+=1 for i in range(0,div+1): if i*d>=div and (i-1)*d<=n-1: temp = n-max((i-1)*d+1,div) ans = max(ans,su[n]-su[n-i]+su[num]-su[num-temp]) print(ans) ``` Yes
106,330
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Submitted Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 # from sys import stdin # input = stdin.readline 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)] try: # sys.setrecursionlimit(int(pow(10,6))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass def pmat(A): for ele in A: print(ele,end="\n") n, d, m = map(int, input().split()) arr = list(map(int, input().split())) dp = [0]*(n+1) arr.sort() count = 0 for i in range(n): dp[i+1] = arr[i] + dp[i] if arr[i] <= m: count += 1 res = dp[count] for i in range(1, n-count+1): if (i-1)*d + i > n: break res = max(res, dp[n]-dp[n-i]+dp[count]-dp[max(0, (i-1)*d-(n-count-i))]) print(res) endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ``` Yes
106,331
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Submitted Solution: ``` import sys input = sys.stdin.readline n, d, m = map(int,input().split()) A = list(map(int,input().split())) from random import randint # for ii in range(100): # n = 7 # d = 5 # m = 1 # A = [randint(1, 20) for i in range(n)] # A = [3, 18, 7, 19, 7, 18, 2] B = [] C = [] for i in range(n): if A[i] > m: B.append(A[i]) else: C.append(A[i]) B.sort(reverse=True) C.sort(reverse=True) # print(B,C) ans = 0 if len(B) == 0: ans = sum(A) else: bmin = (n-len(C)-1) // (d+1) + 1 bmax = min(len(B), (n-1)//(d+1) + 1) bind = bmin cind = n-((bmin-1)*(d+1)+1) - 1 ans0 = sum(B[:bmin]) ans0 += sum(C[:cind+1]) ans = ans0 # print(bind,cind,ans0) for i in range(cind-len(C)+1): C.append(0) while bind < bmax: ans0 += B[bind] bind += 1 for i in range(d+1): if len(C) > 0 and cind >= 0: # print(cind) ans0 -= C[cind] cind -= 1 ans = max(ans0, ans) # print(bind,cind,ans0) print(ans) # import itertools # D = list(itertools.permutations([i for i in range(n)])) # ans1 = 0 # for i in range(len(D)): # ans2 = 0 # mu = 0 # for j in range(n): # if mu == 0: # ans2 += A[D[i][j]] # if A[D[i][j]] > m: # mu = d # else: # mu -= 1 # ans1 = max(ans1,ans2) # if ans!=ans1: # print(ans,ans1,A) ``` Yes
106,332
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Submitted Solution: ``` #Bhargey Mehta (Junior) #DA-IICT, Gandhinagar import sys, math mod = 10**9 + 7 def solve(test_index): n, d, m = map(int, input().split()) a, b = [], [] for x in map(int, input().split()): if x <= m: a.append(x) else: b.append(x) a = sorted(a, reverse=True) b = sorted(b, reverse=True) if len(b) == 0: print(sum(a)) return else: ans = sum(a) + b[0] for i in range(1, len(a)): a[i] += a[i-1] for i in range(1, len(b)): b[i] += b[i-1] for blocks in range(1, len(b)): use = len(a) - blocks * d if use < 0: continue elif use == 0: smallSum = 0 else: smallSum = a[use-1] bigSum = b[blocks] ans = max(ans, smallSum + bigSum) print(ans) return if 'PyPy' not in sys.version: sys.stdin = open('input.txt', 'r') sys.setrecursionlimit(100000) num_tests = 1 #num_tests = int(input()) for test in range(1, num_tests+1): #print("Case #{}: ".format(test), end="") solve(test) ``` No
106,333
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Submitted Solution: ``` import sys import math input=sys.stdin.readline n,d,m=map(int,input().split()) a=[int(i) for i in input().split() if i!='\n'] a.sort() lo=-1 for i in range(n): if a[i]>m: lo=i break pref=[0] for i in range(n): pref.append(pref[-1]+a[i]) if n<=(d+1): print(pref[lo]) else: ans=0 if (n-1)%(d+1)==0: pq=math.ceil((n-1)/(d+1))+1 else: pq=math.ceil((n-1)/(d+1)) pos=min(n-lo,pq) hi=n-pos for i in range(hi,n): ans+=a[i] lo-=1 for i in range((pos-1)*(d+1),n-1): ans+=a[lo] lo-=1 lo+=1 if m==31335: print(ans) while True: if lo<0 or hi>=n: break if (pref[lo]-pref[max(0,lo-d-1)])>a[hi]: ans-=a[hi] ans+=(pref[lo]-pref[max(0,lo-d-1)]) lo-=(d+1) hi+=1 else: break print(ans) ``` No
106,334
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Submitted Solution: ``` import sys import math input=sys.stdin.readline n,d,m=map(int,input().split()) a=[int(i) for i in input().split() if i!='\n'] a.sort() lo=-1 for i in range(n): if a[i]>m: lo=i break pref=[0] for i in range(n): pref.append(pref[-1]+a[i]) if n<=(d+1): print(pref[lo]) else: ans=0 if (n-1)%(d+1)==0: pq=math.ceil((n-1)/(d+1))+1 else: pq=math.ceil((n-1)/(d+1)) pos=min(n-lo,pq) hi=n-pos for i in range(hi,n): ans+=a[i] lo-=1 if d==31335: print(ans,a[lo]) for i in range((pos-1)*(d+1),n-1): if lo<0: break ans+=a[lo] lo-=1 lo+=1 if d==31335: print(hi,(pos-1)*(d+1)) while True: if lo<0 or hi>=n: break if (pref[lo]-pref[max(0,lo-d-1)])>a[hi]: ans-=a[hi] ans+=(pref[lo]-pref[max(0,lo-d-1)]) lo-=(d+1) hi+=1 else: break print(ans) ``` No
106,335
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48. Submitted Solution: ``` import sys import math input=sys.stdin.readline n,d,m=map(int,input().split()) a=[int(i) for i in input().split() if i!='\n'] a.sort() lo=-1 for i in range(n): if a[i]>m: lo=i break pref=[0] for i in range(n): pref.append(pref[-1]+a[i]) if n<=(d+1): print(pref[lo]) else: ans=0 if (n-1)%(d+1)==0: pq=math.ceil((n-1)/(d+1))+1 else: pq=math.ceil((n-1)/(d+1)) pos=min(n-lo,pq) hi=n-pos for i in range(hi,n): ans+=a[i] lo-=1 for i in range((pos-1)*(d+1),n-1): ans+=a[lo] lo-=1 lo+=1 if d==31335: print(ans) while True: if lo<0 or hi>=n: break if (pref[lo]-pref[max(0,lo-d-1)])>a[hi]: ans-=a[hi] ans+=(pref[lo]-pref[max(0,lo-d-1)]) lo-=(d+1) hi+=1 else: break print(ans) ``` No
106,336
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given four integers n, m, l and r. Let's name a tuple (x_1, y_1, x_2, y_2) as good if: 1. 1 ≤ x_1 < x_2 ≤ n; 2. 1 ≤ y_2 < y_1 ≤ m; 3. x_1 ⋅ y_1 = x_2 ⋅ y_2; 4. l ≤ x_1 ⋅ y_1 ≤ r. Find any good tuple for each x_1 from 1 to n inclusive. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5). The second line contains two integers l and r (1 ≤ l ≤ r ≤ nm). Output For each x_1 from 1 to n inclusive: * if there are no such four integers, print -1; * otherwise, print four integers x_1, y_1, x_2 and y_2. If there are multiple answers, print any of them. Examples Input 8 20 91 100 Output -1 -1 -1 -1 -1 6 16 8 12 -1 -1 Input 4 5 1 10 Output 1 2 2 1 2 3 3 2 -1 -1 Input 5 12 16 60 Output -1 2 9 3 6 3 8 4 6 4 5 5 4 -1 Submitted Solution: ``` n, m = [int(i) for i in input().split()] l, r = [int(i) for i in input().split()] for x1 in range(1, n+1): for x2 in range(1, n+1): for y1 in range(1, m+1): for y2 in range(1, m+1): if x1 != x2 and y1 != y2: if 1 <= x1 < x2 <= n: if 1 <= y2 < y1 <= m: if x1*y1 == x2*y2: if l <= x1*y1 <= r: print(x1, y1, x2, y2) break else: print(-1) ``` No
106,337
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given four integers n, m, l and r. Let's name a tuple (x_1, y_1, x_2, y_2) as good if: 1. 1 ≤ x_1 < x_2 ≤ n; 2. 1 ≤ y_2 < y_1 ≤ m; 3. x_1 ⋅ y_1 = x_2 ⋅ y_2; 4. l ≤ x_1 ⋅ y_1 ≤ r. Find any good tuple for each x_1 from 1 to n inclusive. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5). The second line contains two integers l and r (1 ≤ l ≤ r ≤ nm). Output For each x_1 from 1 to n inclusive: * if there are no such four integers, print -1; * otherwise, print four integers x_1, y_1, x_2 and y_2. If there are multiple answers, print any of them. Examples Input 8 20 91 100 Output -1 -1 -1 -1 -1 6 16 8 12 -1 -1 Input 4 5 1 10 Output 1 2 2 1 2 3 3 2 -1 -1 Input 5 12 16 60 Output -1 2 9 3 6 3 8 4 6 4 5 5 4 -1 Submitted Solution: ``` #import random n, m = map(int, input().split()) l, r = map(int, input().split()) pointer=0; c=-1; x1=1;x2=1;y1=1;y2=1; print("\n") for x1 in range(1,n+1): for x2 in range(1,n+1): if x1 <= x2: for y1 in range(1,m+1): for y2 in range(1,m+1): if y1>=y2: if (x1*y1) == (x2*y2): if x1*y1 <= r and x1*y1 >= l: if x1 != x2: if (x1<x2) and pointer == 0 : print(x1,y1,x2,y2) pointer=1; else: break; c=1; else: c=0; else: if c==1: c=1; else: c=0; if c == 0: print("-1") c=-1; pointer = 0; ``` No
106,338
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given four integers n, m, l and r. Let's name a tuple (x_1, y_1, x_2, y_2) as good if: 1. 1 ≤ x_1 < x_2 ≤ n; 2. 1 ≤ y_2 < y_1 ≤ m; 3. x_1 ⋅ y_1 = x_2 ⋅ y_2; 4. l ≤ x_1 ⋅ y_1 ≤ r. Find any good tuple for each x_1 from 1 to n inclusive. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5). The second line contains two integers l and r (1 ≤ l ≤ r ≤ nm). Output For each x_1 from 1 to n inclusive: * if there are no such four integers, print -1; * otherwise, print four integers x_1, y_1, x_2 and y_2. If there are multiple answers, print any of them. Examples Input 8 20 91 100 Output -1 -1 -1 -1 -1 6 16 8 12 -1 -1 Input 4 5 1 10 Output 1 2 2 1 2 3 3 2 -1 -1 Input 5 12 16 60 Output -1 2 9 3 6 3 8 4 6 4 5 5 4 -1 Submitted Solution: ``` n, m = map(int, input().split()) l, r = map(int, input().split()) for x1 in range(1, n + 1): y1 = l // x1 if l % x1: y1 -=- 1 if y1 > m: print(-1) continue p = x1 * y1 s = True if n < m: for x2 in reversed(range(x1 + 1, n + 1)): if not p % x2: y2 = p // x2 if y2 < m: s = False print(x1, y1, x2, y2) break else: for y2 in reversed(range(1, y1)): if not p % y2: x2 = p // y2 if x2 <= n: s = False print(x1, y1, x2, y2) break if s: print(-1) ``` No
106,339
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given four integers n, m, l and r. Let's name a tuple (x_1, y_1, x_2, y_2) as good if: 1. 1 ≤ x_1 < x_2 ≤ n; 2. 1 ≤ y_2 < y_1 ≤ m; 3. x_1 ⋅ y_1 = x_2 ⋅ y_2; 4. l ≤ x_1 ⋅ y_1 ≤ r. Find any good tuple for each x_1 from 1 to n inclusive. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5). The second line contains two integers l and r (1 ≤ l ≤ r ≤ nm). Output For each x_1 from 1 to n inclusive: * if there are no such four integers, print -1; * otherwise, print four integers x_1, y_1, x_2 and y_2. If there are multiple answers, print any of them. Examples Input 8 20 91 100 Output -1 -1 -1 -1 -1 6 16 8 12 -1 -1 Input 4 5 1 10 Output 1 2 2 1 2 3 3 2 -1 -1 Input 5 12 16 60 Output -1 2 9 3 6 3 8 4 6 4 5 5 4 -1 Submitted Solution: ``` def other(y,n,m,i): for j in range(1,int(i**0.5)+1): if i%j==0 and i//j!=y and j!=i//j: if (j<=n and i//j<=m) or (j<=m and i//j<=n): #print(j,i//j) k=[j,i//j] sorted(k) return k return [] def factors(y,n,m,l,r): for i in range(l,r+1): if i%y==0 and i//y<=m and y!=i//y: k=other(y,n,m,i) if len(k)>0: return [y,i//y,k[0],k[1]] return -1 n,m=map(int,input().split()) l,r=map(int,input().split()) ls=[] for i in range(1,n+1): #print(i) p=factors(i,n,m,l,r) if p!=-1: h=sorted(p) if p!=-1 and h not in ls : ls.append(h) u=list(map(str,p)) print(' '.join(u)) else: print(-1) ``` No
106,340
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Tags: binary search, data structures, two pointers Correct Solution: ``` from typing import TypeVar, Generic, Callable, List import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') T = TypeVar('T') class SegmentTree(Generic[T]): __slots__ = ["size", "tree", "identity", "op", "update_op"] def __init__(self, size: int, identity: T, op: Callable[[T, T], T], update_op: Callable[[T, T], T]) -> None: self.size = size self.tree = [identity] * (size * 2) self.identity = identity self.op = op self.update_op = update_op def build(self, a: List[T]) -> None: tree = self.tree tree[self.size:self.size + len(a)] = a for i in range(self.size - 1, 0, -1): tree[i] = self.op(tree[i << 1], tree[(i << 1) + 1]) def find(self, left: int, right: int) -> T: left += self.size right += self.size tree, result, op = self.tree, self.identity, self.op while left < right: if left & 1: result = op(tree[left], result) left += 1 if right & 1: result = op(tree[right - 1], result) left, right = left >> 1, right >> 1 return result def update(self, i: int, value: T) -> None: op, tree = self.op, self.tree i = self.size + i tree[i] = self.update_op(tree[i], value) while i > 1: i >>= 1 tree[i] = op(tree[i << 1], tree[(i << 1) + 1]) n = int(input()) a = list(map(int, input().split())) segt = SegmentTree[int](n + 10, 10**9, min, max) segt.build([-1] * (n + 10)) prev = [-1] * (n + 10) flag = [0] + [1] * (n + 10) for i, x in enumerate(a): if x != 1: flag[1] = 0 left = segt.find(1, x) if left > prev[x]: flag[x] = 0 prev[x] = i segt.update(x, i) for i, f in enumerate(flag): if f and not (prev[i] < segt.find(1, i) < n): print(i) exit() ```
106,341
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Tags: binary search, data structures, two pointers Correct Solution: ``` from math import inf, log2 class SegmentTree: def __init__(self, array, func=max): self.n = len(array) self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1 self.func = func self.default = 0 if self.func != min else inf self.data = [self.default] * (2 * self.size) self.process(array) def process(self, array): self.data[self.size : self.size+self.n] = array for i in range(self.size-1, -1, -1): self.data[i] = self.func(self.data[2*i], self.data[2*i+1]) def query(self, alpha, omega): """Returns the result of function over the range (inclusive)!""" if alpha == omega: return self.data[alpha + self.size] res = self.default alpha += self.size omega += self.size + 1 while alpha < omega: if alpha & 1: res = self.func(res, self.data[alpha]) alpha += 1 if omega & 1: omega -= 1 res = self.func(res, self.data[omega]) alpha >>= 1 omega >>= 1 return res def update(self, index, value): """Updates the element at index to given value!""" index += self.size self.data[index] = value index >>= 1 while index: self.data[index] = self.func(self.data[2*index], self.data[2*index+1]) index >>= 1 # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if not True else 1): n = int(input()) #n, m = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) a = list(map(int, input().split())) if a == [1]*n: print(1) quit() di = {} for i in range(n): if a[i] not in di: di[a[i]] = [-1] di[a[i]] += [i] queries = [] dx = [0]*(n+69) for each in di: di[each] += [n] for j in range(len(di[each])-1): if di[each][j]+1 == n or di[each][j+1]-1 == -1:continue queries += [[di[each][j]+1, di[each][j+1]-1, each]] queries += [[0, n-1, n+3]] queries = sorted(queries, key=lambda x: x[1]) st = SegmentTree([69696969] + [-1]*(n+69), func=min) j = 0 for i in range(n): st.update(a[i], i) while j < len(queries) and queries[j][1] == i: less_than = queries[j][0] alpha, omega = 0, n+1 while alpha < omega: mid = (alpha+omega) // 2 if st.query(alpha, mid) < less_than: omega = mid else: alpha = mid + 1 #print(queries[j][0], queries[j][1], "->", omega) dx[queries[j][2]] = max(dx[queries[j][2]], omega) j += 1 ans = 0 for i in range(1, n+2): if dx[i] != i: ans = i break if dx[n+3] == ans: ans += 1 #print(dx) print(ans) ```
106,342
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Tags: binary search, data structures, two pointers Correct Solution: ``` class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.range = [(-1,n)] * 2 * self.num # 配列の値を葉にセット for i in range(n): self.tree[self.num + i] = init_val[i] self.range[self.num + i] = (i,i) # 構築していく for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) self.range[i] = (self.range[2 * i][0],self.range[2 * i + 1][1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 n = int(input()) p = list(map(int,input().split())) pos = [[] for i in range(n+2)] for i in range(n): pos[p[i]].append(i) query = [[] for i in range(n)] for i in range(1,n+2): for j in range(len(pos[i])-1): L = pos[i][j] + 1 R = pos[i][j+1] - 1 if L<=R: query[R].append((L,i)) if pos[i]: if pos[i][0]!=0: query[pos[i][0]-1].append((0,i)) if pos[i][-1]!=n-1: query[n-1].append((pos[i][-1]+1,i)) else: query[n-1].append((0,i)) #print(query) flag = [False for i in range(n+3)] init = [-1]*(n+2) init[0] = n lastappeared = SegmentTree(init,min,-1) for i in range(n): lastappeared.update(p[i],i) for l,val in query[i]: check = lastappeared.bisect_l(0,n+2,l-1) #print(l,i,val,check) #pp = [lastappeared.tree[j+lastappeared.num] for j in range(n)] if check>=val or check==-1: flag[val] = True for i in range(1,n+3): if not flag[i]: print(i) break ```
106,343
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Tags: binary search, data structures, two pointers Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) ans = 1 last, pre = [0] * (n + 2), [n + 2] * (n + 2) b = [n + 1] * (n + 1) for i in range(1, n + 1): pre[i] = last[a[i - 1]] last[a[i - 1]] = i def update(i, x): while i <= n: b[i] = min(b[i], x) i += i & -i def getmin(i): ans = n + 2 while i: ans = min(ans, b[i]) i -= i & -i return ans vis = [False] * (n + 3) for i in range(1, n + 1): update(i, last[i]) for i in range(1, n + 2): if last[i] != n and getmin(i - 1) > last[i]: vis[i] = True for i in range(n, 0, -1): update(a[i - 1], pre[i]) if pre[i] != i - 1 and getmin(a[i - 1] - 1) > pre[i]: vis[a[i - 1]] = True ans = 1 while vis[ans]: ans += 1 print(ans) ```
106,344
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Tags: binary search, data structures, two pointers Correct Solution: ``` import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for k in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10**19 MOD = 10**9 + 7 EPS = 10**-10 class SegTree: def __init__(self, n, func, intv, A=[]): self.n = n self.func = func self.intv = intv n2 = 1 while n2 < n: n2 <<= 1 self.n2 = n2 self.tree = [self.intv] * (n2 << 1) if A: for i in range(n): self.tree[n2+i] = A[i] for i in range(n2-1, -1, -1): self.tree[i] = self.func(self.tree[i*2], self.tree[i*2+1]) def update(self, i, x): i += self.n2 self.tree[i] = x while i > 0: i >>= 1 self.tree[i] = self.func(self.tree[i*2], self.tree[i*2+1]) def add(self, i, x): self.update(i, self.get(i) + x) def query(self, a, b): l = a + self.n2 r = b + self.n2 s = self.intv while l < r: if r & 1: r -= 1 s = self.func(s, self.tree[r]) if l & 1: s = self.func(s, self.tree[l]) l += 1 l >>= 1 r >>= 1 return s def get(self, i): return self.tree[i+self.n2] def all(self): return self.tree[1] def print(self): for i in range(self.n): print(self.get(i), end=' ') print() N = INT() A = LIST() seg = SegTree(N+2, min, INF, [-1]*(N+2)) mex = [0] * (N+2) if sorted(A, reverse=1)[0] != 1: mex[1] = 1 for i in range(N): if A[i] == 1: seg.update(A[i], i) continue prev = seg.get(A[i]) l = 1 r = A[i] mn = seg.query(l, r) if mn > prev: mex[A[i]] = 1 seg.update(A[i], i) for a in range(2, N+2): prev = seg.get(a) l = 1 r = a mn = seg.query(l, r) if mn > prev: mex[a] = 1 ans = N + 2 for i in range(1, N+2): if not mex[i]: ans = i break print(ans) ```
106,345
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Tags: binary search, data structures, two pointers 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 class SegmentTree: def __init__(self, data, default=0, func=min): self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value while idx: idx >>= 1 self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) n=int(data()) a=mdata() if len(set(a))==1 and 1 in a: out(1) exit() S=SegmentTree(list(range(-n-1,0)),INF) m=[0]*(n+1) for i in range(n): x=a[i] ind=S.query(0,x) if ind<0: m[ind]=1 else: m[a[ind]-1]=1 S.__setitem__(x-1,i) for i in range(n+1): ind = S.query(0,i+1) if ind < 0: m[ind] = 1 else: m[a[ind] - 1] = 1 for i in range(n+1): if m[i]==0: out(i+1) exit() out(n+2) ```
106,346
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Tags: binary search, data structures, two pointers Correct Solution: ``` class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val);self.segfunc = segfunc;self.ide_ele = ide_ele;self.num = 1 << (n - 1).bit_length();self.tree = [ide_ele] * 2 * self.num;self.range = [(-1,n)] * 2 * self.num for i in range(n):self.tree[self.num + i] = init_val[i];self.range[self.num + i] = (i,i) for i in range(self.num - 1, 0, -1):self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]);self.range[i] = (self.range[2 * i][0],self.range[2 * i + 1][1]) def update(self, k, x): k += self.num;self.tree[k] = x while k > 1:self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]);k >>= 1 def query(self, l, r): res = self.ide_ele;l += self.num;r += self.num while l < r: if l & 1:res = self.segfunc(res, self.tree[l]);l += 1 if r & 1:res = self.segfunc(res, self.tree[r - 1]);l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num;r += self.num;Lmin = -1;Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1:Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x:Rmin = r-1 l >>= 1;r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num:pos = (2 * pos if self.tree[2 * pos] <= x else 2 * pos + 1) return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num:pos = (2*pos if self.tree[2 * pos] <=x else 2 * pos + 1) return pos-self.num else:return -1 n = int(input());p = list(map(int,input().split()));pos = [[] for i in range(n+2)];query = [[] for i in range(n)] for i in range(n):pos[p[i]].append(i) for i in range(1,n+2): for j in range(len(pos[i])-1): L = pos[i][j] + 1;R = pos[i][j+1] - 1 if L<=R:query[R].append((L,i)) if pos[i]: if pos[i][0]!=0:query[pos[i][0]-1].append((0,i)) if pos[i][-1]!=n-1:query[n-1].append((pos[i][-1]+1,i)) else:query[n-1].append((0,i)) flag = [False for i in range(n+3)];init = [-1]*(n+2);init[0] = n;lastappeared = SegmentTree(init,min,-1) for i in range(n): lastappeared.update(p[i],i) for l,val in query[i]: check = lastappeared.bisect_l(0,n+2,l-1) if check>=val or check==-1:flag[val] = True for i in range(1,n+3): if not flag[i]:print(i);break ```
106,347
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Tags: binary search, data structures, two pointers Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) mn = [-1 for _ in range(n*4)] def Set(c, ss, se, qi, f): if ss==se: mn[c] = f else: mid = ss+se>>1 if qi<=mid: Set(c*2, ss, mid, qi, f) else: Set(c*2+1, mid+1, se, qi, f) mn[c] = min(mn[c*2], mn[c*2+1]) def Walk(c, ss, se, k): if ss==se: return ss+1 if mn[c]>k else ss mid = ss+se>>1 if mn[c*2]>k: return Walk(c*2+1, mid+1, se, k) else: return Walk(c*2, ss, mid, k) las = [-1 for _ in range(n+2)] was = [False for _ in range(n+3)] for i in range(n): if las[a[i]]!=i-1: was[Walk(1, 1, n, las[a[i]])] = True las[a[i]] = i Set(1, 1, n, a[i], i) for i in range(1, n+2): if las[i]!=n-1: was[Walk(1, 1, n, las[i])] = True ans = 1 while was[ans]: ans += 1 print(ans) ```
106,348
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Submitted 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 class SegmentTree: def __init__(self, data, default=0, func=min): self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value while idx: idx >>= 1 self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) n=int(data()) a=mdata() if len(set(a))==1 and 1 in a: out(1) exit() S=SegmentTree(list(range(-n-1,0)),INF) m=[0]*(n+1) for i in range(n): x=a[i] ind=S.query(0,x) if ind<0: m[ind]=1 else: m[a[ind]-1]=1 S.__setitem__(x-1,i) for i in range(n+1): ind = S.query(0,i+1) if ind < 0: m[ind] = 1 else: m[a[ind] - 1] = 1 for i in range(n+1): if m[i]==0: out(i+1) exit() out(n+2) ``` Yes
106,349
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Submitted Solution: ``` import collections n = int(input()) a = list(map(int, input().split())) def lowbit(x): return x & -x def add(x, k): i = x while i <= n: tree[i] = max(tree[i], k) i += lowbit(i) def query(x): ans = 0 i = x while i > 0: ans = max(ans, tree[i]) i -= lowbit(i) return ans G = collections.defaultdict(list) tree = collections.defaultdict(int) for i in range(1, n + 2): G[i].append(0) for i in range(1, n + 1): G[a[i - 1]].append(i) for i in range(1, n + 2): G[i].append(n + 1) ans = 1 for i in range(1, n + 2): flag, sz = 0, len(G[i]) if sz == n + 2: ans = i break for j in range(1, sz): f = query(G[i][j - 1] + 1) if f < G[i][j]: flag = 1 if not flag: break for j in range(1, sz): f = G[i][j - 1] + 1 add(f, G[i][j]) ans = i + 1 print(ans) ``` Yes
106,350
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Submitted Solution: ``` import collections n = int(input()) a = list(map(int, input().split())) def lowbit(x): return x & -x def add(x, k): while x <= n: tree[x] = max(tree[x], k) x += lowbit(x) def query(x): ans = 0 while x > 0: ans = max(ans, tree[x]) x -= lowbit(x) return ans G = collections.defaultdict(list) tree = collections.defaultdict(int) for i in range(1, n + 2): G[i].append(0) for i in range(1, n + 1): G[a[i - 1]].append(i) for i in range(1, n + 2): G[i].append(n + 1) ans = 1 for i in range(1, n + 2): flag, sz = 0, len(G[i]) if sz == n + 2: ans = i break for j in range(1, sz): f = query(G[i][j - 1] + 1) if f < G[i][j]: flag = 1 if not flag: break for j in range(1, sz): f = G[i][j - 1] + 1 add(f, G[i][j]) ans = i + 1 print(ans) ``` Yes
106,351
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Submitted Solution: ``` import functools n = int(input()) arr = [int(x) for x in input().split()] functools.lru_cache(None) def mex(a): a.sort() i = 1 while i in a: i += 1 return i grand_arr = [] for l in range(1, n+1): for i in range(0, n-l+1): subset = arr[i:i+l] print(subset) grand_arr.append(mex(subset)) print(mex(grand_arr)) ``` No
106,352
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Submitted Solution: ``` def mex(a, n): p = [0 for i in range(n + 1)] for i in range(n): if i + 1 in a: p[i] = 1 return p.index(0) + 1 n = int(input()) t = list(map(int, input().split())) res = [] for i in range(1, n + 1): for j in range(n - i + 1): res.append(mex(set(t[j:j + i]), n)) print(mex(set(res), n)) ``` No
106,353
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Submitted Solution: ``` from __future__ import division, print_function import os,sys from io import BytesIO, IOBase input=sys.stdin.readline I=lambda:list(map(int,input().split())) if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def msi(): return map(str,input().strip().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(1024000) thread = threading.Thread(target=main) thread.start() #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace abc='abcdefghijklmnopqrstuvwxyz' abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25} mod=1000000007 #mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def getKey(item): return item[1] def sort2(l):return sorted(l, key=getKey,reverse=True) def d2(n,m,num):return [[num for x in range(m)] for y in range(n)] def isPowerOfTwo (x): return (x and (not(x & (x - 1))) ) def decimalToBinary(n): return bin(n).replace("0b","") def ntl(n):return [int(i) for i in str(n)] def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1))) def ceil(x,y): if x%y==0: return x//y else: return x//y+1 def powerMod(x,y,p): res = 1 x %= p while y > 0: if y&1: res = (res*x)%p y = y>>1 x = (x*x)%p return res def gcd(x, y): while y: x, y = y, x % y return x def isPrime(n) : # Check Prime Number or not if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def main(): n,=I() l=I() now=[] cur=1 for i in range(n): if l[i]==cur: now.append([i,i]) if not now: print(1) sys.exit() def mex(l): r=sorted(set(l)) for i in range(len(r)): if i+1!=r[i]: return i+1 return len(r)+1 cur=2 an=2 while 1: nxt=[] while now: a,b=now.pop() if a-1>=0 and l[a-1]==cur: nxt.append([a-1,b]) if b+1<n and l[b+1]==cur: nxt.append([a,b+1]) if not nxt: an=cur+1 break now=nxt cur+=1 if cur>mex(l): an-=1 print(an) main() ``` No
106,354
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6 Submitted Solution: ``` ultimmex = [] def mex(x): x = list(set(x)) x.sort() if x[0]!=1: return 1 else: for i in range(1, len(x)+2): if i not in x: return i break n = int(input()) lst = list(map(int, input().split())) temp = list(lst) for i in range(1, len(temp)): temp.pop(0) ultimmex.append(mex(temp)) for i in range(1, len(lst)): lst.pop() ultimmex.append(mex(lst)) print(mex(ultimmex)) ``` No
106,355
Provide tags and a correct Python 3 solution for this coding contest problem. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Tags: dp, math, probabilities Correct Solution: ``` from sys import stdin t = int(stdin.readline()) for _ in range(t): n, m = tuple(int(x) for x in stdin.readline().split()) data = tuple(int(x) for x in stdin.readline().split()) exp = [] for _ in range(m): exp.append(stdin.readline().split()) for last in range(n-1, -1, -1): if last != data[last] - 1: break else: print(1.0) continue ans = 1 for e in exp: if int(e[0]) > last: ans *= (1-float(e[1])) print(1-ans) ```
106,356
Provide tags and a correct Python 3 solution for this coding contest problem. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Tags: dp, math, probabilities Correct Solution: ``` import sys input=sys.stdin.readline #print=sys.stdout.write #sys.setrecursionlimit(100000) #from heapq import * #from collections import deque as dq #from math import ceil,floor,sqrt,gcd,log #import bisect as bs #from collections import Counter #from collections import defaultdict as dc #from functools import reduce #from functools import lru_cache ri=lambda:int(input()) rl=lambda:list(map(int,input().split())) rs=lambda:input().strip("\r\n") for _ in range(ri()): n,m=rl() a=rl() pos=n-1 while a[pos]==pos+1 and pos>=0: pos-=1 ans=1 if pos==-1: ans=0 for _ in range(m): r,p=input().split() r=int(r)-1 p=float(p) if r>=pos: ans=ans*(1-p) print(1-ans) ```
106,357
Provide tags and a correct Python 3 solution for this coding contest problem. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Tags: dp, math, probabilities Correct Solution: ``` t = int(input()) while t > 0: t -= 1 n, m = map(int, input().split()) lst = list(map(int, input().split())) lst.reverse() k = n for i in lst: if i == k: k -= 1 else: break ans = 1.0 for i in range(m): r, p = map(float, input().split()) if r >= k: ans *= (1.0 - p) if k == 0: print(1) else: print("{:.6f}".format(1.0 - ans)) ```
106,358
Provide tags and a correct Python 3 solution for this coding contest problem. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Tags: dp, math, probabilities Correct Solution: ``` for _ in range (int(input())) : n,m = list(map(int, input().split())) a = list(map(int, input().split())) x = n for i in range (n-1,-1,-1) : if x != a[i] : break x -= 1 ans = 1 for _ in range (m) : i,p = list(map(float, input().split())) if int(i)>=x : ans *= (1-p) if (a == sorted(a)) : print(1) continue print('%.15f'%(1-ans)) ```
106,359
Provide tags and a correct Python 3 solution for this coding contest problem. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Tags: dp, math, probabilities Correct Solution: ``` t = int(input()) for _ in range(t): n,k = map(int,input().split()) arr = list(map(int,input().strip().split()))[:n] p = 1;i = n-1 while i >=0: if arr[i] != i+1: break i-=1 ans = 0 i+=1 for z in range(k): a,b = map(float,input().split()) if a >= i: ans += p*b p = p*(1-b) if i == 0: ans = 1.0 print(ans) ```
106,360
Provide tags and a correct Python 3 solution for this coding contest problem. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Tags: dp, math, probabilities Correct Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline() # -------------------------------------------------------------------- def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # sys.setrecursionlimit(100000) # import random # from functools import reduce # from functools import lru_cache # from heapq import * # from collections import deque as dq # import math # import bisect as bs # from collections import Counter # from collections import defaultdict as dc def find(data, mi, ma, s): res.add(s) a, b = [], [] p = (mi + ma) >> 1 for v in data: if v <= p: a.append(v) else: b.append(v) if a and b: sa = sum(a) find(a, mi, max(a), sa) find(b, min(b), ma, s - sa) for _ in range(N()): n, m = RL() a = RLL() key = 0 for i in range(n - 1, -1, -1): if a[i] != i + 1: key = i + 1 break if key == 0: for _ in range(m): input() print(1) else: s = 1 for _ in range(m): o = input().split() i = int(o[0]) p = float(o[1]) if i >= key: s *= 1 - p print(1 - s) ```
106,361
Provide tags and a correct Python 3 solution for this coding contest problem. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Tags: dp, math, probabilities Correct Solution: ``` def proba(arr,po): maxi=None for i in range(len(arr)-1,-1,-1): if arr[i]!=i+1: maxi=i break if maxi==None: return 1.0 ans=1 po=sorted(po,key=lambda s:s[0],reverse=True) for i in range(len(po)): if po[i][0]>=maxi: ans*=(1-po[i][1]) else: break return 1-ans for i in range(int(input())): a,b=map(int,input().strip().split()) lst=list(map(int,input().strip().split())) blanck=[] for i in range(b): x,y=map(str,input().strip().split()) x=int(x)-1 y=float(y) blanck.append([x,y]) print(proba(lst,blanck)) ```
106,362
Provide tags and a correct Python 3 solution for this coding contest problem. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Tags: dp, math, probabilities Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): for _ in range(int(input())): n,m = map(int,input().split()) a = list(map(int,input().split())) j = n-1 while j != -1 and a[j] == j+1: j -= 1 if j == -1: for _ in range(m): x = input() print(1) continue ans = 0 fac = 1 for _ in range(m): r,p = map(float,input().split()) r = int(r) if r >= j+1: ans += fac*p fac *= (1-p) print(ans) #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() ```
106,363
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Submitted Solution: ``` for _ in range(int(input())): n,m = list(map(int,input().split())) arr = list(map(int,input().split())) req = n for i in range(n-1,-1,-1): if arr[i]==i+1: req = i else: break ans = 0 p = 1 for i in range(m): x,y = list(map(float,input().split())) x = int(x) if x>=req: ans+=(p*y) p = p*(1-y) if req==0: ans = 1 print(ans) ``` Yes
106,364
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Submitted Solution: ``` t=int(input()) for asd in range(t): n,k=map(int,input().split()) ar=list(map(int,input().split())) br=[] for i in range(1,n+1): br.append(i) idx=n-1 while idx>=0: if ar[idx]!=br[idx]: break idx-=1 ans=1.0 if idx<=0: ans=1.000000000 for i in range(k): a,p=input().split() else: for i in range(k): a,p = input().split() a=int(a) p=float(p) a-=1 if a>=idx: ans=ans*(1.0-p) ans=1-ans print("%.9f"%ans) ``` Yes
106,365
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Submitted Solution: ``` import sys,math from functools import reduce N=int(input()) for i in range(N): n,m=list(map(int,sys.stdin.readline().strip().split())) arr=list(map(int,sys.stdin.readline().strip().split())) lmt=n for pos in range(n-1,-1,-1): if arr[pos]==pos+1: lmt-=1 else: break P=[] for _ in range(m): a,b=list(map(float,sys.stdin.readline().strip().split())) if int(a)>=lmt: P.append(b) if lmt==0: print(1.0) elif len(P)==0: print(0.0) else: # print(P) print(1-reduce(lambda x,y:x*y,(map(lambda x:1-x,P)))) ``` Yes
106,366
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Submitted Solution: ``` for _ in range(int(input())): n,m = map(int, input().split()) a = [*map(int, input().split())] t = 1 for i in range(n-1,-1,-1): if a[i]!=i+1:t = i+1;break ans = 1 for i in range(m): r, p = map(float, input().split()) if r>=t: ans *= (1-p) print(1-ans if t>1 else 1) ``` Yes
106,367
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Submitted Solution: ``` import sys, os # import numpy as np from math import sqrt, gcd, ceil, log, floor from bisect import bisect, bisect_left from collections import defaultdict, Counter, deque from heapq import heapify, heappush, heappop from itertools import permutations input = sys.stdin.readline read = lambda: list(map(int, input().strip().split())) # read_f = lambda file: list(map(int, file.readline().strip().split())) # from time import time # sys.setrecursionlimit(5*10**6) MOD = 10**9 + 7 def f(row, a, b, curr, mat, pref): if row >= 0 and row < len(mat) and a >= 0 and b < len(mat[0]): # print(a, b, pref[row][a], pref[row][b], curr) if a == 0: return(pref[row][b] == curr) else: return((pref[row][b] - pref[row][a-1]) == curr) else: return(False) def main(): # file1 = open("C:\\Users\\shank\\Desktop\\Comp_Code\\input.txt", "r") # n = int(file1.readline().strip()); # arr = list(map(int, file1.read().strip().split(" "))) # file1.close() # n = int(input()) ans = [] for _ in range(int(input())): n, m = read(); arr = [0]+read() till = n+1 for i in range(n, 0, -1): if i != arr[i]: till = i+1 break p = [0]*(n+1) for i in range(m): a, prob = input().strip().split() a = int(a); prob = float(prob) p[a] = prob s = 1 for i in range(n, 0, -1): if i < till-1: s = s*p[i] + s*(1.00000000-p[i]) else: s = s*(1.0000000-p[i]) if arr == sorted(arr): print(1.000000000) # ans.append(1.0000000) else: print(1.0000000 - s) # ans.append(round((1.0000000 - s), 6)) # print(("\n").join(map(str, ans))) # print(("\n").join(map(str, ans))) # file = open("output.txt", "w") # file.write(ans+"\n") # file.close() if __name__ == "__main__": main() """ abcabcabc """ ``` No
106,368
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Submitted Solution: ``` for w in range(int(input())): n,m=tuple(map(int,input().split())) a=list(map(int,input().split())) d={} x=-1 for i in reversed(range(n)): if(a[i]!=i+1): x=i+1 break for i in range(m): l1=input().split() r=int(l1[0]) p=float(l1[1]) if(r>=x): d[r]=p d1=sorted(list(d.keys())) ans=0 y=1 i=len(d1)-1 while(i>=0): ans+=y*d[d1[i]] y*=(1-d[d1[i]]) i-=1 if(d1[0]>x): ans+=y print(ans) #print(d,x) ``` No
106,369
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Submitted Solution: ``` from sys import stdin t=int(stdin.readline()) for _ in range(t): n,k=map(int,stdin.readline().split()) arr=list(map(int,stdin.readline().split())) srr=sorted(arr) prob=0 prev=0 di={} for i in range(k): a,b=map(float,stdin.readline().split()) di[int(a)]=b counter=0 for i in range(n): if arr[i]==srr[i]: if srr[i] in di: prob=prob*(1-di[srr[i]])+di[srr[i]] else: counter=1 if srr[i] in di: prob=di[srr[i]] else: prob=0 if counter==0: print(1) else: print(round(prob,6)) ``` No
106,370
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment. Submitted Solution: ``` t = int(input()) for _ in range(t): n, m = map(int, input().split()) a = list(map(int, input().split())) lc = n-1 for i in range(n-1, 0, -1): if (a[i] == i+1): lc = i else: break if (lc == 0): print(1) break ans = 1.0 for _ in range(m): data = input().split() r = int(data[0]) p = float(data[1]) if (r >= lc): ans *= 1-p print("{:.6f}".format(1-ans)) ``` No
106,371
Provide tags and a correct Python 3 solution for this coding contest problem. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Tags: binary search, data structures, dp Correct Solution: ``` def find(x): pre=[0]*(n+1) cur=0 for i in range(n): if(a[i]<x): cur-=1 else: cur+=1 if(i>=k-1): if(cur-pre[i-k]>0): return 1 pre[i]=min(pre[i-1],cur) return 0 n,k=map(int,input().split()) a=list(map(int,input().split())) l=1 r=n while(l<=r): m=(l+r)//2 if(find(m)): l=m+1 else: r=m-1 print(r) ```
106,372
Provide tags and a correct Python 3 solution for this coding contest problem. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Tags: binary search, data structures, dp Correct Solution: ``` n, k = map(int, input().split()) a = [int(i) for i in input().split()] l = 1 r = n + 1 while r - l > 1: mid = (r + l) // 2 b = [1 if i >= mid else -1 for i in a] for i in range(1, len(b)): b[i] += b[i - 1] ans = False if b[k - 1] > 0: ans = True mn = 0 for i in range(k, len(b)): mn = min(mn, b[i - k]) if b[i] - mn > 0: ans = True if ans: l = mid else: r = mid print(l) ```
106,373
Provide tags and a correct Python 3 solution for this coding contest problem. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Tags: binary search, data structures, dp Correct Solution: ``` from sys import stdin from collections import Counter from math import pow, sqrt, factorial, log10, log from itertools import permutations, combinations, combinations_with_replacement input = stdin.readline def li(): return list(map(int, input().split())) def mp(): return map(int, input().split()) def inp(): return int(input()) def pr(n): return stdout.write(str(n)+"\n") INF = float('inf') def solve(): n, k = mp() a = li() l, r = 1, n while l < r: m = (l+r+1) >> 1 b = [0] * (n+1) for i in range(n): if a[i] >= m: b[i+1]=1 else: b[i+1]=-1 b[i+1]+=b[i] x, f = 0, 0 for i in range(k, n+1): x = min(x, b[i-k]) if x<b[i]: f=1 break if f: l=m else: r = min(r-1, m) print(l) t = 1 for i in range(t): solve() ```
106,374
Provide tags and a correct Python 3 solution for this coding contest problem. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Tags: binary search, data structures, dp Correct Solution: ``` import sys input = sys.stdin.readline n,k=map(int,input().split()) A=list(map(int,input().split())) MIN=min(A) MAX=max(A) OK=MIN NG=MAX+1 seg_el=1<<((n+1).bit_length()) def update(n,x,seg_el): i=n+seg_el SEG[i]=x i>>=1 while i!=0: SEG[i]=max(SEG[i*2],SEG[i*2+1]) i>>=1 def getvalues(l,r): L=l+seg_el R=r+seg_el ANS=-1<<30 while L<R: if L & 1: ANS=max(ANS , SEG[L]) L+=1 if R & 1: R-=1 ANS=max(ANS , SEG[R]) L>>=1 R>>=1 return ANS while NG-OK>1: mid=(OK+NG)//2 S=[0] for a in A: if a>=mid: S.append(S[-1]+1) else: S.append(S[-1]-1) SEG=[-1<<30]*(2*seg_el) for i in range(n+1): SEG[i+seg_el]=S[i] for i in range(seg_el-1,0,-1): SEG[i]=max(SEG[i*2],SEG[i*2+1]) #print(mid,SEG) for i in range(n+1-k): t=S[i] if getvalues(i+k,n+2)>t: OK=mid #print(mid,i,i+k,n+2) break else: NG=mid print(OK) ```
106,375
Provide tags and a correct Python 3 solution for this coding contest problem. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Tags: binary search, data structures, dp Correct Solution: ``` def proc1(m: int, arr: list) -> None: global cnt1 global cnt2 cnt1 = [0] * (n + 2) cnt2 = [0] * (n + 2) for i in range(1, n + 1): if arr[i] < m: cnt1[i] = cnt1[i-1] - 1 else: cnt1[i] = cnt1[i-1] + 1 for i in range(n, 0, -1): if arr[i] < m: cnt2[i] = max(0, cnt2[i+1] - 1) else: cnt2[i] = cnt2[i+1] + 1 pass def proc2(m: int, k: int, arr: list) -> bool: global cnt1 global cnt2 proc1(m, arr) for i in range(1, n + 1): if i + k > n + 1: break c1 = cnt1[i + k - 1] - cnt1[i - 1] c2 = cnt2[i + k] if c1 + c2 > 0: return True return False def solve(n: int, k: int, arr: list) -> int: arr2 = arr[1:n+1] arr2.sort() l, r = 1, n while l + 1 < r: mid = (l + r) // 2 median = arr2[mid - 1] if proc2(median, k, arr): l = mid else: r = mid - 1 if proc2(arr2[r - 1], k, arr): return arr2[r - 1] else: return arr2[l - 1] pass if __name__ == '__main__': read = input().split() n = int(read[0]) k = int(read[1]) read = input().split() arr = [0] * (n + 2) for i in range(1, n + 1): arr[i] = int(read[i - 1]) ans = solve(n, k, arr) print(ans) pass ```
106,376
Provide tags and a correct Python 3 solution for this coding contest problem. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Tags: binary search, data structures, dp Correct Solution: ``` N,K=map(int,input().split()) A=list(map(int,input().split())) L,R=1,N while L<R: M=(L+R+1)>>1 B=[0]*(N+1) for i in range(N): if A[i]>=M: B[i+1]=1 else: B[i+1]=-1 B[i+1]+=B[i] X=0 F=0 for i in range(K,N+1): X=min(X,B[i-K]) if X<B[i]: F=1 break if F: L=M else: R=min(R-1,M) print(L) ```
106,377
Provide tags and a correct Python 3 solution for this coding contest problem. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Tags: binary search, data structures, dp Correct Solution: ``` ####################################################################################################################### # Author: BlackFyre # Language: PyPy 3.7 ####################################################################################################################### from sys import stdin, stdout, setrecursionlimit from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log, log2 from random import seed, randint from datetime import datetime from collections import defaultdict as dd, deque from heapq import merge, heapify, heappop, heappush, nsmallest from bisect import bisect_left as bl, bisect_right as br, bisect from collections import defaultdict as dd mod = pow(10, 9) + 7 mod2 = 998244353 # setrecursionlimit(3000) def inp(): return stdin.readline().strip() def iinp(): return int(inp()) def out(var, end="\n"): stdout.write(str(var) + "\n") def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end) def lmp(): return list(mp()) def mp(): return map(int, inp().split()) def smp(): return map(str, inp().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)] def remadd(x, y): return 1 if x % y else 0 def ceil(a, b): return (a + b - 1) // b def def_value(): return 0 n,k = mp() a = lmp() b = sorted(a) l,r = 1,n while l<r: mid = (l+r+1)//2 x = mid tmp = a.copy() for i in range(n): if tmp[i]>=x: tmp[i]=1 else: tmp[i]=-1 sm = l1d(n+1) for i in range(n): sm[i+1]=sm[i]+tmp[i] flg=False mn = 0 for i in range(-1,n-k): mn = min(mn,sm[i+1]) if sm[i+k+1]-mn>0: flg=True break if flg: l=mid else: r=mid-1 print(l) ```
106,378
Provide tags and a correct Python 3 solution for this coding contest problem. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Tags: binary search, data structures, dp Correct Solution: ``` import sys, math, itertools, random, bisect from collections import defaultdict INF = sys.maxsize def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def input(): return sys.stdin.readline().strip() mod = 10**9 + 7 def check(a,m,k): b = [1 if i>=m else -1 for i in a] for i in range(1,len(b)): b[i] += b[i-1] ans = False if b[k-1]>0: ans = True mn = 0 for i in range(k,len(b)): mn = min(mn,b[i-k]) if b[i]-mn>0: ans = True return ans for _ in range(1): n,k = get_ints() a = get_array() l,r = 1,n while l<=r: m = (l+r)//2 if check(a,m,k): l = m+1 else: r = m-1 print(r) ```
106,379
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Submitted Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def check(n,k,a,mid): a = list(map(lambda xx:xx>=mid,a)) cul = sum(a[:k]) if cul >= k//2+1: return 1 mino,mine,pr = 0,10**10,0 for i in range(n-k): pr += a[i] cul += a[i+k] if i&1: mino = min(mino,pr-(i+1)//2) else: mine = min(mine,pr-i//2) if (((k+i)&1 and cul-min(mino,mine-1) >= (k+i+1)//2+1) or (not (k+i)&1 and cul-min(mino,mine) >= (k+i+1)//2+1)): return 1 return 0 def main(): n,k = map(int,input().split()) a = list(map(int,input().split())) hi,lo,ans = n,1,1 while hi >= lo: mid = (hi+lo)//2 if check(n,k,a,mid): lo = mid+1 ans = mid else: hi = mid-1 print(ans) # 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() ``` Yes
106,380
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Submitted Solution: ``` n, k = map(int, input().split()) a = [int(x) for x in input().split()] p = [0] * n mx = [0] * n def check(x): for i in range(n): cur = 1 if a[i] >= x else -1 if i == 0: mx[i] = p[i] = cur else: p[i] = p[i - 1] + cur mx[i] = max(cur, mx[i - 1] + cur) for i in range(k - 1, n): if p[i] - p[i - k + 1] + mx[i - k + 1] > 0: return 1 return 0 ans = 0 for j in range(20, -1, -1): ans += 1 << j if not check(ans): ans -= 1 << j print(ans) ``` Yes
106,381
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Submitted Solution: ``` def check(A, x, k): n = len(A) C = [0] for i in range(len(A)): if A[i] >= x: C.append(C[-1] + 1) else: C.append(C[-1] - 1) mn = C[0] for i in range(k, n + 1): mn = min(mn, C[i - k]) if C[i] - mn > 0: return True return False n, k = map(int, input().split()) begin = 1 A = list(map(int, input().split())) end = max(A) while end - begin >= 2: middle = (end + begin) // 2 if check(A, middle, k): begin = middle else: end = middle if check(A, end, k): print(end) else: print(begin) ``` Yes
106,382
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Submitted Solution: ``` n,k=map(int,input().split()) l=list(map(int,input().split())) lo=1 hi=n ans=1 z=0 while lo<=hi: m=(lo+hi)//2 l2=[] l1=[0]*n for i in range(n): if l[i]<m: l2.append(-1) else: l2.append(1) for i in range(1,n): l2[i]+=l2[i-1] c=-n for i in range(n-1,-1,-1): c=max(c,l2[i]) l1[i]=c c=n f=0 if l1[k-1]>0: f=1 c=l2[0] for i in range(1,n-k+1): a=l1[i+k-1] if a-c>0: f=1 break c=min(c,l2[i]) if f: ans=m lo=m+1 else: hi=m if lo==hi: if z: break z+=1 print(ans) ``` Yes
106,383
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Submitted Solution: ``` import math import statistics n, k = map(int, input().split(' ')) v = list(map(int, input().split(' '))) ans = 0 for i in range(0, n-k+1): j = k - 1 while i + j < n: ans = max(ans, statistics.median(v[i:i+j])) j += 1 print(math.floor(ans)) ``` No
106,384
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Submitted Solution: ``` import bisect n, k = map(int,input().split()) arr = list(map(int,input().split())) n = 200000 k = 100000 arr = range(200000) temp = [] for i in range(k): bisect.insort(temp,arr[i]) ans = temp[(k-1)//2] for i in range(k,n): loc = bisect.bisect_left(temp,arr[i-k]) temp.pop(loc) bisect.insort(temp,arr[i]) ans = max(ans, temp[(k-1)//2]) print(ans) ``` No
106,385
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Submitted Solution: ``` n,k=[int(x) for x in input().split()] arr=[int(x) for x in input().split()] arr.sort() ans1=arr[n-k:] ans2=arr[n-k-1:] a=ans1[(len(ans1)+1)//2-1] b=ans2[(len(ans2)+1)//2-1] print(min(a,b)) ``` No
106,386
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3. Submitted Solution: ``` from sys import stdin from collections import Counter from math import pow, sqrt, factorial, log10, log from itertools import permutations, combinations, combinations_with_replacement input = stdin.readline def li(): return list(map(int, input().split())) def mp(): return map(int, input().split()) def inp(): return int(input()) def pr(n): return stdout.write(str(n)+"\n") INF = float('inf') def solve(): n, k = mp() a = li() b = list(a) b.sort() if k == 2: return b[-2] res = 0 origin = 0 while (origin <= n-k): i = origin j = origin + k while(j <= n): t = a[i:j] t.sort() l = len(t) m = (l+1)//2 res = max(res, m) i+=1 j+=1 origin+=1 return res t = 1 for i in range(t): print(solve()) ``` No
106,387
Provide tags and a correct Python 3 solution for this coding contest problem. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Tags: dp, math, number theory Correct Solution: ``` # your code goes here import math import sys import argparse def main(): input = sys.stdin.readline n, d = list(map(int,input().split())) a = list(map(float,input().split())) b = [] for i in range(0,n): b.append(int(a[i])) a[i] = math.log(a[i]) mlog = sum(a) f = [[0.0 for j in range(0,11)] for i in range(0,n)] c = [[[0,0] for j in range(0,11)] for i in range(0,n)] ans = [] for i in range(n): if (i != 0) : for j in range(10): f[i][j] = f[i-1][j] c[i][j][0] = c[i-1][j][0] c[i][j][1] = c[i-1][j][1] for j in range(10): if f[i-1][j]+a[i] > f[i][(j*b[i])%10]: f[i][(j*b[i])%10] = f[i-1][j]+a[i] c[i][(j*b[i])%10][0] = i c[i][(j*b[i])%10][1] = j if f[i][b[i]%10] < a[i]: f[i][b[i]%10] = a[i] c[i][b[i]%10][0] = i c[i][b[i]%10][1] = -1 continue if (i == 0) : for j in range(10): f[i][j] = math.log(0.0001)-mlog c[i][j][0] = -1 c[i][j][1] = -1 f[i][b[0]%10] = a[0] c[i][b[0]%10][0] = 0 c[i][b[0]%10][1] = -1 continue if(f[n-1][d] <= 0): print(-1) return 0 x,y = c[n-1][d][0],c[n-1][d][1] while y != -1: ans.append(b[x]) u = x-1 if u < 0: break x = c[u][y][0] y = c[u][y][1] if x >= 0: ans.append(b[x]) print(len(ans)) print(" ".join(list(map(str,ans)))) if __name__ == "__main__": if 0: print("test2") main() ```
106,388
Provide tags and a correct Python 3 solution for this coding contest problem. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Tags: dp, math, number theory Correct Solution: ``` import math n, d = map(int, input().split()) a = [int(_) for _ in input().split()] dp = [[-1e10] * 10 for _ in range(n + 1)] come = [[(0, 0, 0) for i in range(10)] for j in range(n + 1)] dp[0][1] = 0 for i in range(n): for j in range(10): val = dp[i][j] + math.log(a[i]) if dp[i + 1][(j * a[i]) % 10] <= val: dp[i + 1][(j * a[i]) % 10] = val come[i + 1][(j * a[i]) % 10] = (i, j, 1) val = dp[i][j] if dp[i + 1][j] <= val: dp[i + 1][j] = val come[i + 1][j] = (i, j, 0) now = n dig = d soln = [] while now > 0: if come[now][dig][2] == 1: soln.append(a[now - 1]) now, dig = come[now][dig][:2] prod = 1 for i in soln: prod = (prod * i) % 10 if prod == d and len(soln) > 0: print(len(soln)) print(' '.join(map(str, soln))) else: print(-1) ```
106,389
Provide tags and a correct Python 3 solution for this coding contest problem. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Tags: dp, math, number theory Correct Solution: ``` # your code goes here import math import sys import argparse def main(): input = sys.stdin.readline n, d = list(map(int,input().split())) a = list(map(float,input().split())) b = [] for i in range(0,n): b.append(int(a[i])) a[i] = math.log(a[i]) mlog = sum(a) f = [[0.0 for j in range(0,11)] for i in range(0,n)] c = [[[0,0] for j in range(0,11)] for i in range(0,n)] ans = [] for i in range(n): if (i != 0) : for j in range(10): f[i][j] = f[i-1][j] c[i][j][0] = c[i-1][j][0] c[i][j][1] = c[i-1][j][1] for j in range(10): if f[i-1][j]+a[i] > f[i][(j*b[i])%10]: f[i][(j*b[i])%10] = f[i-1][j]+a[i] c[i][(j*b[i])%10][0] = i c[i][(j*b[i])%10][1] = j if f[i][b[i]%10] < a[i]: f[i][b[i]%10] = a[i] c[i][b[i]%10][0] = i c[i][b[i]%10][1] = -1 continue if (i == 0) : for j in range(10): f[i][j] = math.log(0.0001)-mlog c[i][j][0] = -1 c[i][j][1] = -1 f[i][b[0]%10] = a[0] c[i][b[0]%10][0] = 0 c[i][b[0]%10][1] = -1 continue if(f[n-1][d] <= 0): print(-1) return 0 x,y = c[n-1][d][0],c[n-1][d][1] while y != -1: ans.append(b[x]) u = x-1 if u < 0: break x = c[u][y][0] y = c[u][y][1] if x >= 0: ans.append(b[x]) print(len(ans)) print(" ".join(list(map(str,ans)))) if __name__ == "__main__": if 0: print("hello") main() ```
106,390
Provide tags and a correct Python 3 solution for this coding contest problem. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Tags: dp, math, number theory Correct Solution: ``` import math import random import sys import time seed = int(time.time()) random.seed(seed) def equalsf(a, b): return abs(a - b) < 1e-6 def solve(N, D, A): lgA = [math.log(a) for a in A] dp = [[None for _ in range(10)] for _ in range(N)] parents = [[-1 for _ in range(10)] for _ in range(N)] for i in range(N): #if i > 0: # print(i - 1, dp[i - 1], file=sys.stderr) # print(i - 1, parents[i - 1], file=sys.stderr) d = A[i] % 10 dp[i][d] = lgA[i] if i == 0: continue # propagate for prev_d in range(10): if dp[i][prev_d] is None or (dp[i - 1][prev_d] is not None and dp[i][prev_d] < dp[i - 1][prev_d]): dp[i][prev_d] = dp[i - 1][prev_d] parents[i][prev_d] = prev_d for prev_d in range(10): if dp[i - 1][prev_d] is None: continue prod_d = (d * prev_d) % 10 cand = dp[i - 1][prev_d] + lgA[i] if dp[i][prod_d] is None or dp[i][prod_d] < cand: dp[i][prod_d] = cand parents[i][prod_d] = prev_d #print(N - 1, dp[N - 1], file=sys.stderr) #print(N - 1, parents[N - 1], file=sys.stderr) #if dp[N - 1][D] is not None: # print("found solution:", round(math.exp(dp[N - 1][d])), file=sys.stderr) #else: # print("no solution", file=sys.stderr) # reconstruct answer ans = [] parent = D for i in range(N - 1, -1, -1): if dp[i][parent] is None: break prev_p = parents[i][parent] if i > 0 and prev_p >= 0: print(i, "cur:", parent, "prev:", prev_p, file=sys.stderr) if dp[i - 1][prev_p] is not None and equalsf(dp[i - 1][prev_p] + lgA[i], dp[i][parent]): ans.append(A[i]) parent = prev_p else: ans.append(A[i]) break return ans def main(): N, D = [int(x) for x in input().strip().split()] A = [int(x) for x in input().strip().split()] ans = solve(N, D, A) if len(ans) == 0: print(-1) else: print(len(ans)) print(' '.join([str(x) for x in ans])) if '__main__'==__name__: main() ```
106,391
Provide tags and a correct Python 3 solution for this coding contest problem. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Tags: dp, math, number theory Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from math import log10 def main(): log = [0]+[log10(i) for i in range(1,1001)] unit = [i%10 for i in range(1001)] n,d = map(int,input().split()) a = list(map(int,input().split())) dp = [[0]*10 for _ in range(n+1)] # unit digit ; index ne = [[i for i in range(10)] for _ in range(n+1)] take = [[0]*10 for _ in range(n+1)] for i in range(n): dp[i+1],uni = dp[i][:],unit[a[i]] for j in range(10): if not dp[i][j]: continue xx,un = dp[i][j]+log[a[i]],unit[j*uni] if xx > dp[i+1][un]: dp[i+1][un],ne[i+1][un],take[i+1][un] = xx,j,1 if log[a[i]] > dp[i+1][uni]: dp[i+1][uni],take[i+1][uni],ne[i+1][uni] = log[a[i]],1,-1 ind,ans = d,[] for i in range(n,0,-1): if take[i][ind]: ans.append(a[i-1]) ind = ne[i][ind] if ind == -1: break if len(ans): print(len(ans)) print(*ans) elif d == 1 and a.count(1): print(1) print(1) else: print(-1) # 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() ```
106,392
Provide tags and a correct Python 3 solution for this coding contest problem. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Tags: dp, math, number theory Correct Solution: ``` import math def main(): n, d = [int(x) for x in input().split()] a = [int(x) for x in input().split()] if d!=5 and d!=0: a = list(filter(lambda x: x%5!=0 ,a)) if d&1: a = list(filter(lambda x: x%2, a)) n = len(a) dp = [[-1e6 for _ in range(10)] for _ in range(n + 1)] path = [[(0, 0, 0) for _ in range(10)] for _ in range(n + 1)] dp[0][1] = 0 for i in range(n): for j in range(10): val = dp[i][j] + math.log(a[i]) if dp[i + 1][(j * a[i])%10] <= val: dp[i + 1][(j * a[i])%10] = val path[i + 1][(j * a[i])%10] = (i, j, 1) val = dp[i][j] if dp[i + 1][j] <= val: dp[i + 1][j] = val path[i + 1][j] = (i, j , 0) ans = [] test, pd = 1, d while n > 0 : if path[n][d][2] == 1: ans.append(a[n - 1]) test = (test * a[n - 1])%10 n,d = path[n][d][:2] if test == pd and len(ans) > 0: print(len(ans)) print(' '.join(map(str, ans))) else: print(-1) if __name__=='__main__': main() ```
106,393
Provide tags and a correct Python 3 solution for this coding contest problem. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Tags: dp, math, number theory Correct Solution: ``` import collections import string import math import copy import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") # n = 0 # m = 0 # n = int(input()) # li = [int(i) for i in input().split()] # s = sorted(li) """ from dataclasses import dataclass @dataclass class point: x: float y: float @dataclass class line: A: float B: float C: float def gety(self, x): return (self.A*x+self.C)/-self.B def getx(self, y): return (self.B*y+self.C)/-self.A def k(self): return -self.A/self.B def b(self): return -self.C/self.B def dist(self, p: point): return abs((self.A*p.x+self.B*p.y+self.C)/(self.A**2+self.B**2)**0.5) def calc_line(u: point, v: point): return line(A=u.y-v.y, B=v.x-u.x, C=u.y*(u.x-v.x)-u.x*(u.y-v.y)) def is_parallel(u: line, v: line) -> bool: f1 = False f2 = False try: k1 = u.k() except: f1 = True try: k2 = v.k() except: f2 = True if f1 != f2: return False return f1 or k1 == k2 def seg_len(_from: point, _to: point): return ((_from.x - _to.x)**2 + (_from.y - _to.y)**2) ** 0.5 def in_range(_from: point, _to: point, _point: point) -> bool: if _from.x < _to.x: if _from.y < _to.y: return _from.x <= _point.x <= _to.x and _from.y <= _point.y <= _to.y else: return _from.x <= _point.x <= _to.x and _from.y >= _point.y >= _to.y else: if _from.y < _to.y: return _from.x >= _point.x >= _to.x and _from.y <= _point.y <= _to.y else: return _from.x >= _point.x >= _to.x and _from.y >= _point.y >= _to.y def intersect(u: line, v: line) -> point: tx = (u.B*v.C-v.B*u.C)/(v.B*u.A-u.B*v.A) if u.B!=0.0: ty = -u.A*tx/u.B - u.C/u.B else: ty = -v.A*tx/v.B - v.C/v.B return point(x=tx, y=ty) def in_direction(_from: point, _to: point, _point: point) -> bool: if _from.x < _to.x: if _from.y < _to.y: return _to.x < _point.x and _to.y < _point.y else: return _to.x < _point.x and _point.y <= _to.y else: if _from.y < _to.y: return _to.x >= _point.x and _to.y < _point.y else: return _to.x >= _point.x and _point.y <= _to.y """ mo = int(1e9+7) def exgcd(a, b): if not b: return 1, 0 y, x = exgcd(b, a % b) y -= a//b * x return x, y def getinv(a, m): x, y = exgcd(a, m) return -1 if x == 1 else x % m def comb(n, b): res = 1 b = min(b, n-b) for i in range(b): res = res*(n-i)*getinv(i+1, mo) % mo # res %= mo return res % mo def quickpower(a, n): res = 1 while n: if n & 1: res = res * a % mo n >>= 1 a = a*a % mo return res def dis(a, b): return abs(a[0]-b[0]) + abs(a[1]-b[1]) def getpref(x): if x > 1: return (x)*(x-1) >> 1 else: return 0 def orafli(upp): primes = [] marked = [False for i in range(upp+3)] prvs = [i for i in range(upp+3)] for i in range(2, upp): if not marked[i]: primes.append(i) for j in primes: if i*j >= upp: break marked[i*j] = True prvs[i*j] = j if i % j == 0: break return primes, prvs def lower_ord(c: str) -> int: return ord(c)-97 def upper_ord(c: str) -> int: return ord(c) - 65 def read_list(): return [int(i) for i in input().split()] def read_int(): s = input().split() if len(s) == 1: return int(s[0]) else: return map(int, s) def ask(s): print(f"? {s}", flush=True) def answer(s): print(f"{s}", flush=True) import random def solve(): n, d = read_int() l = read_list() # dp = [[0 for i in range(10)] for i in range(n)] dp = {} pv = [] for i in l: cd = copy.deepcopy(dp) cp = {} for k, v in dp.items(): lg = math.log(i,2) if v+lg >cd.get(k*i%10,0): # prvcd = cd[k*i%10] cp[v+lg] = v cd[k*i%10] = v+lg # cd[k*i%10] = max(cd.get(k*i%10, 1), v+math.log(i,2)) lg = math.log(i,2) if lg > cd.get(i%10, 0): cp[lg]=0 cd[i%10] = lg pv.append(cp) # cd[i%10] = max(cd.get(i%10, 1), math.log(i,2)) dp = cd sel = [] if d not in dp: print(-1) else: # print(dp[d]) # c = int(round(2**dp[d])) # print(pv) c = dp[d] # rc = round(c,14) while pv: fac = pv.pop() curfac = l.pop() if c in fac: sel.append(curfac) c = fac[c] # for i in l: # if c%i==0: # sel.append(i) # c//=i print(len(sel)) print(*sel) # print(dp.get(d, -1)) # fi = open('C:\\cppHeaders\\CF2020.12.17\\test.data', 'r') # def input(): return fi.readline().rstrip("\r\n") # primes, prv = orafli(10001) solve() # t = int(input()) # for ti in range(t): # print(f"Case #{ti+1}: ", end='') # solve() ```
106,394
Provide tags and a correct Python 3 solution for this coding contest problem. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Tags: dp, math, number theory Correct Solution: ``` #------------------Important Modules------------------# from sys import stdin,stdout from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import * from random import * input=stdin.readline prin=stdout.write from random import sample from collections import Counter,deque from fractions import * from math import sqrt,ceil,log2,gcd #dist=[0]*(n+1) mod=10**9+7 """ class DisjSet: def __init__(self, n): self.rank = [1] * n self.parent = [i for i in range(n)] def find(self, x): if (self.parent[x] != x): self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): xset = self.find(x) yset = self.find(y) if xset == yset: return if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset elif self.rank[xset] > self.rank[yset]: self.parent[yset] = xset else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 """ def f(arr,i,j,d,dist): if i==j: return nn=max(arr[i:j]) for tl in range(i,j): if arr[tl]==nn: dist[tl]=d #print(tl,dist[tl]) f(arr,i,tl,d+1,dist) f(arr,tl+1,j,d+1,dist) #return dist def ps(n): cp=0;lk=0;arr={} #print(n) #cc=0; while n%2==0: n=n//2 #arr.append(n);arr.append(2**(lk+1)) lk+=1 for ps in range(3,ceil(sqrt(n))+1,2): lk=0 cc=0 while n%ps==0: n=n//ps #cc=1 #arr.append(n);arr.append(ps**(lk+1)) lk+=1 if n!=1: #lk+=1 #arr[n]=1 #ans*=n; lk+=1 return False #return arr #print(arr) return True #count=0 #dp=[[0 for i in range(m)] for j in range(n)] #[int(x) for x in input().strip().split()] def gcd(x, y): while(y): x, y = y, x % y return x # Driver Code def factorials(n,r): #This calculates ncr mod 10**9+7 slr=n;dpr=r qlr=1;qs=1 mod=10**9+7 for ip in range(n-r+1,n+1): qlr=(qlr*ip)%mod for ij in range(1,r+1): qs=(qs*ij)%mod #print(qlr,qs) ans=(qlr*modInverse(qs))%mod return ans def modInverse(b): qr=10**9+7 return pow(b, qr - 2,qr) #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func def power(arr): listrep = arr subsets = [] for i in range(2**len(listrep)): subset = [] for k in range(len(listrep)): if i & 1<<k: subset.append(listrep[k]) subsets.append(subset) return subsets def pda(n) : list = [] for i in range(1, int(sqrt(n) + 1)) : if (n % i == 0) : if (n // i == i) : list.append(i) else : list.append(n//i);list.append(i) # The list will be printed in reverse return list def dis(xa,ya,xb,yb): return sqrt((xa-xb)**2+(ya-yb)**2) #### END ITERATE RECURSION #### #=============================================================================================== #----------Input functions--------------------# def ii(): return int(input()) def ilist(): return [int(x) for x in input().strip().split()] def islist(): return list(map(str,input().split().rstrip())) def inp(): return input().strip() def google(test,ans): return "Case #"+str(test)+": "+str(ans); def overlap(x1,y1,x2,y2): if x2>y1: return y1-x2 if y1>y2: return y2-x2 return y1-x2; ###-------------------------CODE STARTS HERE--------------------------------########### def pal(s): k=len(s) n=len(s)//2 for i in range(n): if s[i]==s[k-1-i]: continue else: return 0 return 1 ######################################################################################### #t=int(input()) t=1 for p in range(t): n,kll=ilist() arr=[-1] arr.extend(ilist()) dp=[[0 for i in range(10)] for j in range(n+1)] pointer=[[[-1 for k in range(3)] for i in range(10)] for j in range(n+1)] pp=[] for i in range(1,n+1): for j in range(10): #dp[i][j]=dp[i-1][j] last=arr[i]%10 for k in range(10): #print(k*last,j) #fs=dp[i-1][k]%10 fs=1 if dp[i-1][k]==0 else k if (fs*last)%10==j: if dp[i][j]<dp[i-1][k]+log2(arr[i]+0.01): pointer[i][j][0]=0 pointer[i][j][1]=i-1 pointer[i][j][2]=k dp[i][j]=max(dp[i-1][k]+log2(arr[i]+0.01),dp[i][j]) #print("dp[i-1][k] ",dp[i-1][k],"dp[i][j] ",dp[i][j],"j ",j,"i ",i,"k ",k) if dp[i][j]<dp[i-1][j]: pointer[i][j][0]=1 pointer[i][j][1]=i-1 pointer[i][j][2]=j dp[i][j]=max(dp[i-1][j],dp[i][j]) ans=dp[n][kll] if ans==0: print(-1) continue #print(ans) ap=n;jp=kll count=0 while True: up=ap if pointer[ap][jp][0]!=0: ap=pointer[up][jp][1] jp=pointer[up][jp][2] elif pointer[ap][jp][0]==0: pp.append(arr[ap]) count+=1 ap=pointer[up][jp][1] jp=pointer[up][jp][2] if ap<=0: break print(count) print(*pp) #byevye ```
106,395
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Submitted Solution: ``` # your code goes here import math import sys import argparse def main(): input = sys.stdin.readline n, d = list(map(int,input().split())) a = list(map(float,input().split())) b = [] for i in range(0,n): b.append(int(a[i])) a[i] = math.log(a[i]) mlog = sum(a) f = [[0.0 for j in range(0,11)] for i in range(0,n)] c = [[[0,0] for j in range(0,11)] for i in range(0,n)] ans = [] for i in range(n): if (i != 0) : for j in range(10): f[i][j] = f[i-1][j] c[i][j][0] = c[i-1][j][0] c[i][j][1] = c[i-1][j][1] for j in range(10): if f[i-1][j]+a[i] > f[i][(j*b[i])%10]: f[i][(j*b[i])%10] = f[i-1][j]+a[i] c[i][(j*b[i])%10][0] = i c[i][(j*b[i])%10][1] = j if f[i][b[i]%10] < a[i]: f[i][b[i]%10] = a[i] c[i][b[i]%10][0] = i c[i][b[i]%10][1] = -1 continue if (i == 0) : for j in range(10): f[i][j] = math.log(0.0001)-mlog c[i][j][0] = -1 c[i][j][1] = -1 f[i][b[0]%10] = a[0] c[i][b[0]%10][0] = 0 c[i][b[0]%10][1] = -1 continue if(f[n-1][d] <= 0): print(-1) return 0 x,y = c[n-1][d][0],c[n-1][d][1] while y != -1: ans.append(b[x]) u = x-1 if u < 0: break x = c[u][y][0] y = c[u][y][1] if x >= 0: ans.append(b[x]) print(len(ans)) print(" ".join(list(map(str,ans)))) if __name__ == "__main__": if 0: print("test1000") main() ``` Yes
106,396
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Submitted Solution: ``` from sys import stdin, stdout from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log from collections import defaultdict as dd, deque from heapq import merge, heapify, heappop, heappush, nsmallest from bisect import bisect_left as bl, bisect_right as br, bisect mod = pow(10, 9) + 7 mod2 = 998244353 def inp(): return stdin.readline().strip() def iinp(): return int(inp()) def out(var, end="\n"): stdout.write(str(var)+"\n") def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end) def lmp(): return list(mp()) def mp(): return map(int, inp().split()) def smp(): return map(str, inp().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)] def remadd(x, y): return 1 if x%y else 0 def ceil(a,b): return (a+b-1)//b def isprime(x): if x<=1: return False if x in (2, 3): return True if x%2 == 0: return False for i in range(3, int(sqrt(x))+1, 2): if x%i == 0: return False return True n, k = mp() arr = lmp() dp = l2d(n+1, 10, -1) for i in range(1, n+1): for j in range(10): dp[i][j] = max(dp[i][j], dp[i-1][j]) if j == arr[i-1]%10: dp[i][j] = max(dp[i][j], round(log(arr[i-1]), 6)) if dp[i-1][j]!=-1: dp[i][(j*arr[i-1])%10] = max(dp[i][(j*arr[i-1])%10], round(dp[i-1][j]+log(arr[i-1]), 6)) ansl = [] j = k flg = True for i in range(n, 0, -1): if dp[i][j] == -1: flg = False print(-1) break if dp[i][j]==dp[i-1][j]: continue elif dp[i][j]==round(log(arr[i-1]), 6): ansl.append(arr[i-1]) break else: ansl.append(arr[i-1]) j = dp[i-1].index(round(dp[i][j]-log(arr[i-1]), 6)) if flg: print(len(ansl)) print(*ansl) ``` Yes
106,397
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Submitted Solution: ``` import time #start_time = time.time() #def TIME_(): print(time.time()-start_time) import os, sys from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string, heapq as h BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def getBin(): return list(map(int,list(input()))) def isInt(s): return '0' <= s[0] <= '9' def ceil_(a,b): return a//b + (a%b > 0) MOD = 10**9 + 7 """ 1: {(1,1) (3,7) (9,9)} 2: {(1,2) (2,6) (3,4) (4,8) (6,7) (8,9)} 3: {(1,3) (7,9)} 4: {(1,4) (2,2) (2,7) (3,8) (4,6) (6,9) (8,8)} 5: {(1,5) (3,5) (5,5) (5,7) (5,9)} 6: {(1,6) (2,3) (2,8) (4,4) (4,9) (6,6) (7,8)} 7: {(1,7) (3,9)} 8: {(1,8) (2,4) (2,9) (3,6) (4,7) (6,8)} 9: {(1,9) (3,3) (7,7)} Include all numbers ending in 1 Numbers ending in 3 go in cycles 3 -> 9 -> 7 -> 1 Let's pairwise multiply the 9s, fourwise multiply the 3s and 7s We either include all 5s or no 5s We definitely include: all 1s all but 3 to 6 of the 3s all but 3 to 6 of the 7s all but 1 to 2 of the 9s all the 5s or none of them 2 4 8 6 4 6 4 6 6 6 6 6 8 4 2 6 19 5 37 6 40 50 27 2 9 45 10 8 40 1 37 14 14 30 29 8 9 """ from random import randint as ri def solve(): N, D = getInts() A = getInts() #N = ri(1,20) #D = ri(1,9) #A = [ri(1,50) for _ in range(N)] #print(N,D) #print(*A) dec = [[] for _ in range(10)] for a in A: dec[a%10].append(a) for i in range(10): dec[i].sort() if D == 0: if not dec[0] and not (dec[2] and dec[5]): print(-1) return else: print(N) print(*A) return else: dec[0] = [] if D == 5: if not dec[5]: print(-1) return else: ans = [] for a in A: if a % 2: ans.append(a) print(len(ans)) print(*ans) return else: dec[5] = [] ans = [] while dec[1]: ans.append(dec[1].pop()) while len(dec[3]) > 6: for _ in range(4): ans.append(dec[3].pop()) while len(dec[7]) > 6: for _ in range(4): ans.append(dec[7].pop()) while len(dec[9]) > 2: for _ in range(2): ans.append(dec[9].pop()) #print(ans) if D % 2: A = [] for i in range(1,10,2): while dec[i]: A.append(dec[i].pop()) best = -1 best_mask = -1 for x in range(1,pow(2,len(A))): mask = bin(x)[2:].zfill(len(A)) tmp = 1 for j in range(len(A)): if mask[j] == '1': tmp *= A[j] if tmp % 10 == D and tmp > best: best = tmp best_mask = mask if best != -1: for j in range(len(A)): if best_mask[j] == '1': ans.append(A[j]) print(len(ans)) print(*ans) return elif (D == 1) and ans: print(len(ans)) print(*ans) return else: print(-1) return while dec[6]: ans.append(dec[6].pop()) while len(dec[2]) > 6: for _ in range(4): ans.append(dec[2].pop()) while len(dec[8]) > 6: for _ in range(4): ans.append(dec[8].pop()) while len(dec[4]) > 2: for _ in range(2): ans.append(dec[4].pop()) #now I need the best mask for digit A_odd = [] A_even = [] for i in range(0,10,2): while dec[i]: A_even.append(dec[i].pop()) while dec[i+1]: A_odd.append(dec[i+1].pop()) best = [-1]*10 best_mask = [-1]*10 if ans: best[1] = 1 best_mask[1] = 0 for x in range(1,pow(2,len(A_odd))): mask = bin(x)[2:].zfill(len(A_odd)) tmp = 1 for j in range(len(A_odd)): if mask[j] == '1': tmp *= A_odd[j] if tmp > best[tmp%10]: best[tmp%10] = tmp best_mask[tmp%10] = x for x in range(1,pow(2,len(A_even))): mask = bin(x)[2:].zfill(len(A_even)) tmp = 1 for j in range(len(A_even)): if mask[j] == '1': tmp *= A_even[j] if tmp > best[tmp%10]: best[tmp%10] = tmp best_mask[tmp%10] = x best_combo = -1 best_pair = [-1,-1] for i in range(0,10,2): for j in range(1,10,2): if best[i] != -1 and best[j] != -1: curr = best[i]*best[j] if curr % 10 == D and curr > best_combo: best_combo = curr best_pair = [i,j] if best[D] > best_combo: x = best_mask[D] mask = bin(x)[2:].zfill(len(A_even)) for j in range(len(A_even)): if mask[j] == '1': ans.append(A_even[j]) print(len(ans)) print(*ans) return #print(best_combo,best_pair) #print(A_even,A_odd) #print(best_mask[2],best_mask[9]) if best_pair == [-1,-1]: print(-1) return k,i = best_pair x = best_mask[i] mask = bin(x)[2:].zfill(len(A_odd)) for j in range(len(A_odd)): if mask[j] == '1': ans.append(A_odd[j]) x = best_mask[k] mask = bin(x)[2:].zfill(len(A_even)) for j in range(len(A_even)): if mask[j] == '1': ans.append(A_even[j]) print(len(ans)) print(*ans) return #for _ in range(getInt()): #print(solve()) solve() #TIME_() ``` Yes
106,398
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6. Submitted Solution: ``` # your code goes here import math import sys import argparse def main(): input = sys.stdin.readline n, d = list(map(int,input().split())) a = list(map(float,input().split())) b = [] for i in range(0,n): b.append(int(a[i])) a[i] = math.log(a[i]) mlog = sum(a) f = [[0.0 for j in range(0,11)] for i in range(0,n)] c = [[[0,0] for j in range(0,11)] for i in range(0,n)] ans = [] for i in range(n): if (i != 0) : for j in range(10): f[i][j] = f[i-1][j] c[i][j][0] = c[i-1][j][0] c[i][j][1] = c[i-1][j][1] for j in range(10): if f[i-1][j]+a[i] > f[i][(j*b[i])%10]: f[i][(j*b[i])%10] = f[i-1][j]+a[i] c[i][(j*b[i])%10][0] = i c[i][(j*b[i])%10][1] = j if f[i][b[i]%10] < a[i]: f[i][b[i]%10] = a[i] c[i][b[i]%10][0] = i c[i][b[i]%10][1] = -1 continue if (i == 0) : for j in range(10): f[i][j] = math.log(0.0001)-mlog c[i][j][0] = -1 c[i][j][1] = -1 f[i][b[0]%10] = a[0] c[i][b[0]%10][0] = 0 c[i][b[0]%10][1] = -1 continue if(f[n-1][d] <= 0): print(-1) return 0 x,y = c[n-1][d][0],c[n-1][d][1] while y != -1: ans.append(b[x]) u = x-1 if u < 0: break x = c[u][y][0] y = c[u][y][1] if x >= 0: ans.append(b[x]) print(len(ans)) print(" ".join(list(map(str,ans)))) if __name__ == "__main__": main() ``` Yes
106,399