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. A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell. An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable. Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met. 1. There is at least one south magnet in every row and every column. 2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement. 3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement. Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets). Input The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively. The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters. Output Output a single integer, the minimum possible number of north magnets required. If there is no placement of magnets that satisfies all conditions, print a single integer -1. Examples Input 3 3 .#. ### ##. Output 1 Input 4 2 ## .# .# ## Output -1 Input 4 5 ....# ####. .###. .#... Output 2 Input 2 1 . # Output -1 Input 3 5 ..... ..... ..... Output 0 Note In the first test, here is an example placement of magnets: <image> In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column. <image> In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets. <image> In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square. <image> In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. Submitted Solution: ``` import sys input = sys.stdin.readline I = lambda : list(input().split()) a,b,=I() flag=0 sparse=dict() cc=cr=0 for i in range(int(a)): x,=I() adj=[] for k in range(int(b)): if k not in sparse: sparse[k]=list() if x[k]=='#': adj.append(k) sparse[k].append(i) if len(adj)==0: cr+=1 elif sorted(adj)!=list(range(min(adj),max(adj)+1)): flag=1 break for keys in list(sparse): if len(sparse[keys])!=0 and (sorted(sparse[keys])!=list(range(min(sparse[keys]),max(sparse[keys])+1))): flag=1 break elif len(sparse[keys])==0: sparse.pop(keys) cc+=1 if flag==0: if cr==cc: flag=0 elif cr==int(a) and cc==int(b): flag=2 print('0') else: flag=1 if flag==1: print('-1') if flag==0: count=0 visited=[] def check(sparse,item,key): global count global visited,a,b if key in sparse: if item in sparse[key]: sparse[key].remove(item) visited.append([key,item]) c=0 if len(sparse[key])==0: sparse.pop(key) if item-1>=0: c+=check(sparse,item-1,key) if item+1<=int(a): c+=check(sparse,item+1,key) if key-1>=0: c+=check(sparse,item,key-1) if key+1<=int(b): c+=check(sparse,item,key+1) if c==0: return 1 else: return c else: return 0 else: return 0 for key in list(sparse): if key in sparse: for item in sparse[key]: if [key,item] not in visited: count+=check(sparse,item,key) print(count) ``` No
104,600
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell. An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable. Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met. 1. There is at least one south magnet in every row and every column. 2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement. 3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement. Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets). Input The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively. The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters. Output Output a single integer, the minimum possible number of north magnets required. If there is no placement of magnets that satisfies all conditions, print a single integer -1. Examples Input 3 3 .#. ### ##. Output 1 Input 4 2 ## .# .# ## Output -1 Input 4 5 ....# ####. .###. .#... Output 2 Input 2 1 . # Output -1 Input 3 5 ..... ..... ..... Output 0 Note In the first test, here is an example placement of magnets: <image> In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column. <image> In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets. <image> In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square. <image> In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. Submitted Solution: ``` import sys input = sys.stdin.buffer.readline def print(val): sys.stdout.write(str(val) + '\n') from collections import deque def find_components(node,graph,n,m,visited): queue = deque([node]) while queue: node = queue[-1] visited.add(node) neighbors = [(node[0]+1,node[1]),(node[0]-1,node[1]),\ (node[0],node[1]+1),(node[0],node[1]-1)] had_neighbors = False for neighbor in neighbors: i,j = neighbor if neighbor not in visited and 0<= i < n and 0<= j < m and graph[i][j] == '#': queue.append(neighbor) had_neighbors = True break if not had_neighbors: queue.pop() def yo(): n,m = map(int,input().split()) graph = [str(input().strip())[2:] for i in range(n)] e_row = 0 e_column = 0 for row in graph: if row == "."*m: e_row = 1 break for j in range(m): same = True for i in range(n): if graph[i][j] != '.': same = False break if same: e_column = 1 break if e_row^e_column == 1: print(-1) return for row in graph: start = m-1 value = '#' for j in range(m): if row[j] == '#': start = j break change = False gap = False for j in range(start+1,m): if row[j] != value: change = True elif change: gap = True if gap: print(-1) break if not gap: for j in range(m): start = n-1 value = '#' for i in range(n): if graph[i][j] == '#': start = i break change = False gap = False for i in range(start+1,n): if graph[i][j] != value: change = True elif change: gap = True if gap: print(-1) break if not gap: visited = set() num_components = 0 for i in range(n): for j in range(m): if (i,j) not in visited and graph[i][j] == '#': num_components += 1 find_components((i,j),graph,n,m,visited) print(num_components) yo() ``` No
104,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell. An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable. Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met. 1. There is at least one south magnet in every row and every column. 2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement. 3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement. Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets). Input The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively. The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters. Output Output a single integer, the minimum possible number of north magnets required. If there is no placement of magnets that satisfies all conditions, print a single integer -1. Examples Input 3 3 .#. ### ##. Output 1 Input 4 2 ## .# .# ## Output -1 Input 4 5 ....# ####. .###. .#... Output 2 Input 2 1 . # Output -1 Input 3 5 ..... ..... ..... Output 0 Note In the first test, here is an example placement of magnets: <image> In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column. <image> In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets. <image> In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square. <image> In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. Submitted Solution: ``` n,m=map(int,input().split()) L=[] for _ in range(n): L.append(list(input())) #print(L) visited=set() islands=[] island=1 for i in range(n): for j in range(m): if (i,j) not in visited and L[i][j]=="#": islands.append(1) stack=[(i,j)] while stack: I,J=stack.pop() visited.add((I,J)) p=[(1,0),(-1,0),(0,1),(0,-1)] for t in p: g,h=I+t[0],J+t[1] if (g,h) not in visited and 0<=g<n and 0<=h<m and L[g][h]=="#": stack.append((g,h)) #mark(i,j,island) island+=1 def checkline(arr): ## print(arr) ## lmn=arr.count("#") ## if lmn==1 or lmn==0: ## return True ## return False ## va=-1 for i in range(len(arr)): if va==2 and arr[i]=="#": return False elif va==1 and arr[i]==".": va=2 elif arr[i]=="#": va=1 return True ans=0 for i in range(n): if not checkline(L[i]): ans=-1 break for j in range(m): B=[] for i in range(n): B.append(L[i][j]) if not checkline(B): ans=-1 break if ans!=-1: p="" if n==1 or m==1: for i in range(n): for j in range(m): p+=L[i][j] if 0<p.count("#")<len(p): print(-1) elif p.count("#")==len(p): print(1) else: print(0) else: print(len(islands)) else: print(-1) ``` No
104,602
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell. An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable. Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met. 1. There is at least one south magnet in every row and every column. 2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement. 3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement. Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets). Input The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively. The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters. Output Output a single integer, the minimum possible number of north magnets required. If there is no placement of magnets that satisfies all conditions, print a single integer -1. Examples Input 3 3 .#. ### ##. Output 1 Input 4 2 ## .# .# ## Output -1 Input 4 5 ....# ####. .###. .#... Output 2 Input 2 1 . # Output -1 Input 3 5 ..... ..... ..... Output 0 Note In the first test, here is an example placement of magnets: <image> In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column. <image> In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets. <image> In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square. <image> In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. Submitted Solution: ``` x,y=[int(i) for i in input().split()] a=[] for i in range(x): a.append(input()) spacer=[0]*x spaces=[] for i in range(y): spaces.append(spacer[::]) tec=['.',0] rowx=[] for i in range(x): rowx.append(tec[::]) rowy=[] for i in range(y): rowy.append(tec[::]) nums=0 for i in range(x): for j in range(y): if a[i][j]=='.': if rowy[j][0]=='#': rowy[j][1]+=1 rowy[j][0]='.' if rowx[i][0]=='#': rowx[i][0]='.' rowx[i][1]+=1 try: if a[i+1][j]=='#': spaces[j][i+1]=1 nums+=1 if a[i][j+1]=='#': spaces[j+1][i]=1 nums+=1 except IndexError: pass else: if rowy[j][0]=='.': rowy[j][1]+=1 rowy[j][0]='#' if rowx[i][0]=='.': rowx[i][1]+=1 rowx[i][0]='#' if spaces[j][i]==0: spaces[j][i]=1 nums+=1 try: if a[i+1][j]=='#': if spaces[j][i+1]==1: nums-=1 spaces[j][i+1]=1 if a[j+1][i]=='#': if spaces[j+1][i]==1: nums-=1 spaces[j+1][i]=1 except IndexError: pass flag=0 summ=0 for i in range(x): summ+=rowx[i][1] if rowx[i][1]>2 or rowx[i][1]==0: flag=1 if summ==0: flag=0 if flag==0: for i in range(y): summ+=rowy[i][1] if rowy[i][1]>2 or rowy[i][1]==0: flag=1 if summ==0: flag=0 if flag==1: print(-1) else: print(nums) ``` No
104,603
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` t = int(input()) def solve(): n, x, m = map(int, input().split()) l = r = x while m > 0: l_i, r_i = map(int, input().split()) if l in range(l_i, r_i + 1) or r in range(l_i, r_i + 1): l = min(l, l_i) r = max(r, r_i) m -= 1 print (r - l + 1) while t > 0: solve() t -= 1 ```
104,604
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` def f(r1,r2): if r1[0]<=r2[0] and r1[1]>=r2[0]: return True elif r1[0]>r2[0] and r2[1]>=r1[0]: return True return False for _ in range(int(input())): n,x,m=map(int,input().split()) ansrange=(x,x) for i in range(m): a,b=map(int,input().split()) res = f((a,b),ansrange) if res: ansrange = (min(a,ansrange[0]),max(ansrange[1],b)) print(ansrange[1]-ansrange[0]+1) ```
104,605
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` from sys import stdin, stdout cin = stdin.readline cout = stdout.write mp = lambda: map(int, cin().split()) for _ in range(int(cin())): n, x, m = mp() #ans = 0 #a = [x, x] y = x for _ in range(m): l, r = mp() if y>=l<=r>=x: #x<=r<=l<=y: x = min(l, x) y = max(y, r) #elif l<=a[1]<=r: # a[0] = min(l, a[0]) # a[1] = r cout(str(y-x+1) + '\n') #print(y-x+1) ```
104,606
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` for z in range(int(input())): n,x,m=map(int,input().split()) x1=x2=x for i in range(m): a,b=map(int,input().split()) if b>=x1 and a<=x2: if a<=x1: x1=a if b>=x2: x2=b print(x2-x1+1) ```
104,607
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` for i in range(int(input())): n, x, m = map(int, input().split()) a, b = x, x for t in range(m): l, r = map(int, input().split()) if r >= a and b >= l: a = min(l, a) b = max(r, b) print(b-a+1) ```
104,608
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` def main(n, x, m, left, right): l, r = n, 0 for i in range(len(left)): if x > right[i]: if left[i] <= l <= right[i]: l = left[i] elif x < left[i]: if left[i] <= r <= right[i]: r = right[i] else: l, r = min(l, left[i]), max(r, right[i]) if r-l+1 <= 0: return 1 return r-l+1 for _ in range(int(input())): n, x, m = [int(i) for i in input().split()] left, right = [], [] for i in range(m): inp = input().split() left.append(int(inp[0])) right.append(int(inp[1])) print(main(n, x, m, left , right)) ```
104,609
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` def main(): t = int(input()) test_case_num = 1 while test_case_num <= t: n, x, m = map(int, input().split()) interval = (x, x) for q in range(m): li, ri = map(int, input().split()) if max(interval[0], li) <= min(interval[1], ri): interval = (min(interval[0], li), max(interval[1], ri)) print(interval[1] - interval[0] + 1) test_case_num += 1 main() ```
104,610
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` t = int(input()) for _ in range(t): n, x , m = map(int, input().rstrip().split(" ")) x = x -1 full_range = [x,x] for i in range(m): l, r = map(int, input().rstrip().split(" ")) l-=1 r-=1 if full_range[0] in range(l, r + 1): full_range[0] = min(l, full_range[0]) full_range[1] = max(r, full_range[1]) elif full_range[1] in range(l, r + 1): full_range[0] = min(l, full_range[0]) full_range[1] = max(r, full_range[1]) print(full_range[1]-full_range[0] + 1) ```
104,611
Provide tags and a correct Python 2 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Tags: math, two pointers Correct Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write mod=10**9+7 def ni(): return int(raw_input()) def li(): return map(int,raw_input().split()) def pn(n): stdout.write(str(n)+'\n') def pa(arr): pr(' '.join(map(str,arr))+'\n') # fast read function for total integer input def inp(): # this function returns whole input of # space/line seperated integers # Use Ctrl+D to flush stdin. return map(int,stdin.read().split()) range = xrange # not for python 3.0+ for t in range(ni()): n,x,m=li() px,py=x,x for i in range(m): x,y=li() if (px<=x and py>=y) or (px>=x and px<=y) or (py>=x and py<=y): px=min(px,x) py=max(y,py) pn(py-px+1) ```
104,612
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Submitted Solution: ``` import io,os input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys def solve(n,x,m,LR): ans_l,ans_r=x,x for l,r in LR: if r<ans_l or l>ans_r: continue ans_l=min(ans_l,l) ans_r=max(ans_r,r) return ans_r-ans_l+1 def main(): t=int(input()) for _ in range(t): n,x,m=map(int,input().split()) LR=[tuple(map(int,input().split())) for _ in range(m)] ans=solve(n,x,m,LR) sys.stdout.write(str(ans)+'\n') if __name__=='__main__': main() ``` Yes
104,613
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Submitted Solution: ``` def shuf(n,x,m): start=-1 end=-1 for i in range(len(m)): if x>=m[i][0] and x<=m[i][1]: start=m[i][0] end=m[i][1] for j in range(i+1,len(m)): if (m[j][0]<=start and m[j][1]>=start) or (m[j][0]<=end and m[j][1]>=end) : start=min(m[j][0],start) end=max(m[j][1],end) break return(end-start+1) t=int(input()) l=[] for i in range(t): n,x,m=list(map(int,input().split())) ml=[] for i in range(m): q=list(map(int,input().split())) ml.append(q) l.append([n,x,ml]) for r in l: print(shuf(*r)) ``` Yes
104,614
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Submitted Solution: ``` t = int(input()) for i in range(t): n,x,m = map(int,input().split()) l,r = x,x for i in range(m): a,b = map(int,input().split()) if a <= l and b >= r: l = a r = b elif a <= l and b >= l: l = a elif a <= r and b >= r: r = b print(r-l+1) ``` Yes
104,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Thu Jun 18 08:25:23 2020 @author: Harshal """ for _ in range(int(input())): n,x,m = map(int,input().split()) l,r=x,x for _ in range(m): L,R=map(int,input().split()) if max(l,L)<=min(r,R): l=min(l,L) r=max(r,R) print( r-l+1) ``` Yes
104,616
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Submitted Solution: ``` for _ in range(int(input())) : n,x,m = map(int,input().split()) l = 0 r = 0 cnt = 0 lock = 0 for _ in range(m) : a,b = map(int,input().split()) if lock == 0 : if x >= a and x <= b : cnt = (b-a) + 1 l = a r = b lock = 1 prev_a = a prev_b = b else : if (prev_a >= a and prev_a <=b ) and (prev_b >=a and prev_b<=b) : if (l-a) >= 0 : cnt+=(l-a) if a < l : l = a if (b-r) >=0 : cnt+=(b-r) if b > r : r = b elif prev_a >= a and prev_a <= b : if (l-a) >= 0 : cnt+=(l-a) l = a elif prev_b >= a and prev_b <= b : if (b-r) >= 0 : cnt+=(b-r) r = b else : continue prev_a = a prev_b = b # print(cnt,l,r) print(cnt) ``` No
104,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Submitted Solution: ``` for _ in range(int(input())): a,b,c=map(int,input().split()) m=b for i in range(c): p,q=map(int,input().split()) if p<=b and b<=q: m=max(m,p,q) print(m) ``` No
104,618
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Submitted Solution: ``` import sys T = int(sys.stdin.readline()) for _ in range(T): n, x, m =map(int, sys.stdin.readline().split()) nowl = -1 nowr = n+1 for _ in range(m): l, r = map(int, sys.stdin.readline().split()) if l<=x<=r and nowl==-1: nowl = l nowr = r if l<=nowl<=r or l<=nowr<=r: nowl = min(nowl, l) nowr = max(nowr, r) print(nowr-nowl+1) ``` No
104,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then the description of t testcases follow. The first line of each test case contains three integers n, x and m (1 ≤ n ≤ 10^9; 1 ≤ m ≤ 100; 1 ≤ x ≤ n). Each of next m lines contains the descriptions of the operations; the i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n). Output For each test case print one integer — the number of indices k such that it is possible to choose the operations so that a_k = 1 in the end. Example Input 3 6 4 3 1 6 2 3 5 5 4 1 2 2 4 1 2 3 3 2 2 3 1 2 Output 6 2 3 Note In the first test case, it is possible to achieve a_k = 1 for every k. To do so, you may use the following operations: 1. swap a_k and a_4; 2. swap a_2 and a_2; 3. swap a_5 and a_5. In the second test case, only k = 1 and k = 2 are possible answers. To achieve a_1 = 1, you have to swap a_1 and a_1 during the second operation. To achieve a_2 = 1, you have to swap a_1 and a_2 during the second operation. Submitted Solution: ``` import sys ip=lambda :sys.stdin.readline().rstrip() # a=list(map(int,ip().split())) # n=int(ip()) for _ in range(int(ip())): n,x,m=map(int,ip().split()) a=[] ans=0 ct=0 p=float('inf') p1=float('inf') for _ in range(m): l,r=map(int,ip().split()) if l==1 and r==n: ans=n if x>=l and x<=r: ct=r-l+1 p=r p1=l if ct and l==p or r==p1: ct+= r-l p=r p1=l ans=max(ans,ct) print(ans) ``` No
104,620
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Tags: constructive algorithms, greedy, math Correct Solution: ``` from math import * t=int(input()) while t: t=t-1 #n=int(input()) n,k=map(int,input().split()) a=list(map(int,input().split())) s=set(a) n=len(s) if n==k: print(1) continue if k==1 and n>1: print(-1) continue elif k==1 and n==1: print(1) continue cnt=0 s=list(s) for i in range(n): j=0 flag=1 lst=s[i] cnt+=1 #print(s) for l in range(i,n): if s[l]==0 and flag: j+=1 flag=0 continue elif s[l]==0: continue if j<k: lst=s[l] s[l]-=s[l] j+=1 else: s[l]-=lst #print(s) if s[n-1]==0: break print(cnt) ```
104,621
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Tags: constructive algorithms, greedy, math Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=300006, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" 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 idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:max(a , b)): """initialize the segment tree with data""" 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 idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <=key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] > k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.count=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right self.temp.count+=1 if not val: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left self.temp.count += 1 self.temp.data = pre_xor def query(self, xor): self.temp = self.root for i in range(31, -1, -1): val = xor & (1 << i) if not val: if self.temp.left and self.temp.left.count>0: self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right and self.temp.right.count>0: self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left self.temp.count-=1 return xor ^ self.temp.data #-------------------------bin trie------------------------------------------- for ik in range(int(input())): n,k=map(int,input().split()) a=list(map(int,input().split())) if k==1: s=set(a) if len(s)!=1: print(-1) else: print(1) else: ans=0 while(sum(a)!=0): ans+=1 cou=0 s=set() last=0 for i in range(n): if cou<k: if a[i] not in s: cou+=1 s.add(a[i]) last=a[i] a[i] = 0 elif cou==k and a[i] in s: a[i]=0 else: a[i]-=last print(ans) ```
104,622
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Tags: constructive algorithms, greedy, math Correct Solution: ``` import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from math import ceil t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) if len(set(a)) <= k: print(1) else: m = -1 n = len(set(a)) for i in range(1, 101): if 1+ceil((n-1)/i) <= k: m = i break print(m) ```
104,623
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Tags: constructive algorithms, greedy, math Correct Solution: ``` import math from sys import stdin from sys import setrecursionlimit setrecursionlimit(100000) def put(): return map(int, stdin.readline().split()) for _ in range(int(input())): # n=int(input()) n,k=put() l=(list(put())) if(len(set(l))<=k): print(1) elif(len(set(l))>1 and k==1): print(-1) else: if((len(set(l))-k)%(k-1)==0): print(1+(len(set(l))-k)//(k-1)) else: print(2+(len(set(l))-k)//(k-1)) ```
104,624
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Tags: constructive algorithms, greedy, math Correct Solution: ``` from math import ceil t = int(input()) for _ in range(t): n, k = map(int, input().split()) A = set(map(int, input().split())) uniq = len(A) if k == 1: if uniq == 1: print(1) else: print(-1) else: print(1 + ceil(max(0, uniq - k) / (k - 1))) ```
104,625
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Tags: constructive algorithms, greedy, math Correct Solution: ``` import math for _ in range(int(input())): n, k = map(int, input().split()) a = list(map(int, input().split())) if k == 1: if len(set(a)) == 1: print(1) else: print(-1) continue count = 0 c = 1 flag = True for i in range(n-1): if a[i] != a[i+1]: count += 1 print(max((count+k-2)//(k-1), 1)) ```
104,626
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Tags: constructive algorithms, greedy, math Correct Solution: ``` from sys import stdin,stdout import math,bisect from collections import Counter,deque,defaultdict L=lambda:list(map(int, stdin.readline().strip().split())) M=lambda:map(int, stdin.readline().strip().split()) I=lambda:int(stdin.readline().strip()) S=lambda:stdin.readline().strip() C=lambda:stdin.readline().strip().split() def pr(a):return(" ".join(list(map(str,a)))) #_________________________________________________# def solve(): n,k = M() a = L() x = len(set(a)) if k>=x: print(1) elif k==1: print(-1) else: print(math.ceil((x-1)/(k-1))) for _ in range(I()): solve() ```
104,627
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Tags: constructive algorithms, greedy, math Correct Solution: ``` for _ in range(int(input())): n,k = map(int,input().split(' ')) ans = 0 arr = [int(num) for num in input().split(' ')] if k==1 and len(set(arr))!=1: ans = -1 elif arr[0]==0 and len(set(arr))==1: ans = 1 else: while (arr[0] !=0 or len(set(arr))!=1): i = 0 a = set() a.add(arr[0]) while i<n and len(set(a))<=k: a.add(arr[i]) if len(a)>k: break else: arr[i] = 0 i = i + 1 for j in range(i,n): arr[j] = arr[j] - arr[i-1] ans = ans + 1 print(ans) ```
104,628
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Submitted Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz/' M=998244353 EPS=1e-6 def Ceil(a,b): return a//b+int(a%b>0) def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() for _ in range(Int()): n,k=value() a=array() dist=len(set(a)) if(k==1): if(dist==1): print(1) else: print(-1) else: ans=0 cur=sorted(set(a)) # print(cur) while(True): ans+=1 d=1 ok=False cur[0]=0 for i in range(1,len(cur)): if(cur[i]!=cur[i-1]): d+=1 if(d==k):key=cur[i] if(d<=k): cur[i]=0 else: ok=True cur[i]=key if(not ok): break print(ans) ``` Yes
104,629
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Submitted Solution: ``` import sys def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') def ceil(x, y=1): return int(-(-x // y)) import math from collections import defaultdict for _ in range(ri()): n,k=ria() l=ria() s=set(l) if k==1 and len(s)>1: wi(-1) elif k==1 and len(s)==1: wi(1) else: x=len(s) if x<=k: wi(1) else: x-=k k-=1 wi(1+math.ceil(x/k)) ``` Yes
104,630
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Submitted Solution: ``` import sys import itertools as it import bisect as bi import math as mt import collections as cc input=sys.stdin.readline S=lambda :list(input().split()) I=lambda:list(map(int,input().split())) for tc in range(int(input())): n,k=I() l=I() nn=len(set(l)) if nn>1 and k-1==0: print(-1) elif k>=nn: print(1) else: print(1+(nn-2)//(k-1)) ``` Yes
104,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Submitted Solution: ``` from collections import * from itertools import * from bisect import * def inp(): return int(input()) def arrinp(): return [int(x) for x in input().split()] def main(): t = inp() for _ in range(t): n,k = arrinp() A = arrinp() distinct = set(A) curr = len(distinct) if(k<=1 and curr>k): print(-1) continue if(curr<=k): print(1) continue m = 0 while(len(distinct)>=k): m += 1 temp = list(distinct) #print(*temp, 'value m:', m) sub = temp[k-1] distinct = set() n = len(temp) l = n-1 while(l>=k-1): distinct.add(temp[l]-sub) l -=1 #print(distinct, 'after 1 list generated') if(len(distinct)>1): m+=1 print(m) if __name__ == '__main__': main() ``` Yes
104,632
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Submitted Solution: ``` import sys try:sys.stdin,sys.stdout=open('in.txt','r'),open('out.txt','w') except:pass ii1=lambda:int(sys.stdin.readline().strip()) # for interger is1=lambda:sys.stdin.readline().strip() # for str iia=lambda:list(map(int,sys.stdin.readline().strip().split())) # for List[int] isa=lambda:sys.stdin.readline().strip().split() # for List[str] mod=int(1e9 + 7);from collections import *;from math import * ###################### Start Here ###################### for _ in range(ii1()): n ,k= iia() arr = iia() arr_set=set(arr) # diff=[] # for i in range(n-1): # diff.append(arr[i+1]-arr[i]) # diff_len=len(set(diff)) # if 0 in diff:diff_len-=1 set_len = len(arr_set) if k==1 and set_len==2: print(-1) continue if set_len==1: print(1) continue if k>=set_len: print(1) if set_len>k: print(2) continue ``` No
104,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Submitted Solution: ``` import sys import math input = lambda: sys.stdin.readline().rstrip() for _ in range(int(input())): n,k=map(int,input().split()) l=[int(x) for x in input().split()] a=len(set(l)) arr=[1,2,3,4,5] if(l==arr and k==3): print(2) elif(k<a and k==1): print(-1) elif(a==k): print(1) else: print(a-k) ``` No
104,634
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Submitted Solution: ``` for aww in range(int(input())): a,b=[*map(int, input().split())] c=[*map(int, input().split())] d=set(c) if(b==1): if(len(d)>1): print(-1) else: print(1) else: x=c[0] e=0 f=0 for i,j in enumerate(c): if(x!=c[i]): x=c[i] e+=1 if(e==b): f+=1 e=0 if(e>0): f+=1 print(f) ``` No
104,635
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + b_{m, j}. In the other word, array a is the sum of arrays b_i. * The number of different elements in the array b_i is at most k for all 1 ≤ i ≤ m. Find the minimum possible value of m, or report that there is no possible m. Input The first line contains one integer t (1 ≤ t ≤ 100): the number of test cases. The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 100, a_n > 0). Output For each test case print a single integer: the minimum possible value of m. If there is no such m, print -1. Example Input 6 4 1 0 0 0 1 3 1 3 3 3 11 3 0 1 2 2 3 3 3 4 4 4 4 5 3 1 2 3 4 5 9 4 2 2 3 5 7 11 13 13 17 10 7 0 1 1 2 3 3 4 5 5 6 Output -1 1 2 2 2 1 Note In the first test case, there is no possible m, because all elements of all arrays should be equal to 0. But in this case, it is impossible to get a_4 = 1 as the sum of zeros. In the second test case, we can take b_1 = [3, 3, 3]. 1 is the smallest possible value of m. In the third test case, we can take b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] and b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]. It's easy to see, that a_i = b_{1, i} + b_{2, i} for all i and the number of different elements in b_1 and in b_2 is equal to 3 (so it is at most 3). It can be proven that 2 is the smallest possible value of m. Submitted Solution: ``` mod = 10**9 + 7 def solve(): ans = -1 n, k = map(int, input().split()) a = list(map(int, input().split())) d = {} for x in a: d[x] = 1 if k == 1: if len(d) != 1: ans = -1 else: ans = 1 else: l = len(d) ans = 1 l -= k ans += (l + k - 2) // (k - 1) print(ans) t = int(input()) while t > 0: solve() t -= 1 ``` No
104,636
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` from bisect import * from collections import * from math import * from heapq import * from typing import List from itertools import * from operator import * from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) #------------------------------------------------------------------------ @lru_cache(None) def fact(x): if x<2: return 1 return fact(x-1)*x @lru_cache(None) def per(i,j): return fact(i)//fact(i-j) @lru_cache(None) def com(i,j): return per(i,j)//fact(j) def linc(f,t,l,r): while l<r: mid=(l+r)//2 if t>f(mid): l=mid+1 else: r=mid return l def rinc(f,t,l,r): while l<r: mid=(l+r+1)//2 if t<f(mid): r=mid-1 else: l=mid return l def ldec(f,t,l,r): while l<r: mid=(l+r)//2 if t<f(mid): l=mid+1 else: r=mid return l def rdec(f,t,l,r): while l<r: mid=(l+r+1)//2 if t>f(mid): r=mid-1 else: l=mid return l def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def binfun(x): c=0 for w in arr: c+=ceil(w/x) return c def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class smt: def __init__(self,l,r,arr): self.l=l self.r=r self.value=(1<<31)-1 if l<r else arr[l] mid=(l+r)//2 if(l<r): self.left=smt(l,mid,arr) self.right=smt(mid+1,r,arr) self.value&=self.left.value&self.right.value #print(l,r,self.value) def setvalue(self,x,val): if(self.l==self.r): self.value=val return mid=(self.l+self.r)//2 if(x<=mid): self.left.setvalue(x,val) else: self.right.setvalue(x,val) self.value=self.left.value&self.right.value def ask(self,l,r): if(l<=self.l and r>=self.r): return self.value val=(1<<31)-1 mid=(self.l+self.r)//2 if(l<=mid): val&=self.left.ask(l,r) if(r>mid): val&=self.right.ask(l,r) return val class UFS: def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue for v in graph[u]: if v not in d or d[v]>d[u]+graph[u][v]: d[v]=d[u]+graph[u][v] heappush(heap,(d[v],v)) return d ''' import time s=time.time() for i in range(2000): print(0) e=time.time() print(e-s) ''' n,k=RL() a=RLL() heap=[] ans=0 def val(x,k): a,b=divmod(x,k) return (a+1)**2*b+a**2*(k-b) for i in range(n): ans+=a[i]**2 cur=-val(a[i],1)+val(a[i],2) heappush(heap,(cur,a[i],1)) #print(ans,heap) k-=n for i in range(k): cur,m,n=heappop(heap) ans+=cur cur=-val(m,n+1)+val(m,n+2) heappush(heap,(cur,m,n+1)) #print(heap,ans) print(ans) ```
104,637
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` import heapq def value(l,parts): len1 = l//parts len2 = len1+1 cnt2 = l%parts cnt1 = parts-cnt2 return (cnt1*len1*len1) + (cnt2*len2*len2 ) def solve(n,k,a): #20 - 6 6 6 = 18, 20 -> 7,7,6 = as evenly as possible i divide i get min of sqs sum #20 -> 6 7 7 = x ,20 //> pq = [] tot = 0 for i in range(n): tot += a[i]*a[i] heapq.heappush(pq,((-value(a[i],1) + value(a[i],2)),a[i],2)) for i in range(k-n): temp = heapq.heappop(pq) tot += temp[0] a,b = temp[1],temp[2] heapq.heappush(pq,((-value(a,b)+value(a,b+1)),a,b+1)) #print(tot,a,b) return tot n,k = map(int,input().split()) a = list(map(int,input().split())) print(solve(n,k,a)) ```
104,638
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Tags: binary search, data structures, greedy, math, sortings 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().rstrip("\r\n") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import sys # sys.setrecursionlimit(5010) from heapq import * # from collections import deque as dq # from math import ceil,floor,sqrt,pow # import bisect as bs # from collections import Counter # from collections import defaultdict as dc n,k = RL() a = RLL() heap = [] dic = [[l,l**2,(l>>1)**2*2 if l&1==0 else (l>>1)**2+((l+1)>>1)**2,2] for l in a] for i in range(n): heap.append((dic[i][2]-dic[i][1],i)) heapify(heap) # print(heap) # print(dic) for _ in range(k-n): _,i = heap[0] dic[i][3]+=1 l,p = dic[i][0],dic[i][3] r,ll = l%p,l//p t = (p-r)*ll**2+r*(ll+1)**2 dic[i][1],dic[i][2] = dic[i][2],t heapreplace(heap,(dic[i][2]-dic[i][1],i)) # print(heap) # print(dic) print(sum(a[1] for a in dic)) ```
104,639
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` import sys from heapq import heapify, heappush, heappop def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)] def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e for l in range(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 N, K = MAP() A = LIST() def calc(a, cnt): d, m = divmod(a, cnt) return d**2 * (cnt-m) + (d+1)**2 * m que = [] for a in A: if a // 2 == 0: que.append((0, 1, a)) else: que.append((calc(a, 2) - calc(a, 1), 1, a)) heapify(que) for _ in range(K-N): val, cnt, a = heappop(que) if a // (cnt+2) == 0: heappush(que, (0, cnt+1, a)) else: heappush(que, (calc(a, cnt+2) - calc(a, cnt+1), cnt+1, a)) ans = 0 for _, cnt, a in que: ans += calc(a, cnt) print(ans) ```
104,640
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=300006, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" 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 idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:a + b): """initialize the segment tree with data""" 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 idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] > k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.count=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right self.temp.count+=1 if not val: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left self.temp.count += 1 self.temp.data = pre_xor def query(self, xor): self.temp = self.root for i in range(31, -1, -1): val = xor & (1 << i) if not val: if self.temp.left and self.temp.left.count>0: self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right and self.temp.right.count>0: self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left self.temp.count-=1 return xor ^ self.temp.data #-------------------------bin trie------------------------------------------- def find(a,left): now=(a%left)*(a//left+1)**2+(left-a%left)*(a//left)**2 left+=1 after=(a%left)*(a//left+1)**2+(left-a%left)*(a//left)**2 return now-after n,k=map(int,input().split()) a=list(map(int,input().split())) ans=0 for i in range(n): ans+=a[i]**2 a=[(-find(a[i],1),a[i],1) for i in range(n)] heapq.heapify(a) su=n while(su<k): e,t,no=heapq.heappop(a) ans+=e su+=1 heapq.heappush(a,(-find(t,no+1),t,no+1)) print(ans) ```
104,641
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` import os import sys from io import BytesIO, IOBase from heapq import heappush, heappop def val(L, P): if L <= P: return L q, r = divmod(L, P) return q * q * (P - r) + (q + 1) * (q + 1) * r def main(): n, k, *a = map(int, sys.stdin.read().split()) pq = [] cost = 0 for x in a: now = val(x, 1) nxt = val(x, 2) cost += now if nxt < now: heappush(pq, (nxt - now, now, x, 2)) for _ in range(k - n): impr, now, L, P = heappop(pq) now += impr cost += impr nxt = val(L, P + 1) if nxt < now: heappush(pq, (nxt - now, now, L, P + 1)) print(cost) # 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) def input(): return sys.stdin.readline().rstrip("\r\n") def getint(): return int(input()) def getints(): return list(map(int, input().split())) def getint1(): return list(map(lambda x: int(x) - 1, input().split())) # endregion if __name__ == "__main__": main() ```
104,642
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase import heapq MOD = 10 ** 5 + 1 def main(): n,k = map(int,input().split()) a = list(map(int,input().split())) target = max((sum(a) + (k - 1)) // k - 100,1) cost = [] currentSplit = [] currentCost = [] for elem in a: currentSplit.append((elem + target - 1) // target) currentCost.append((elem // currentSplit[-1]) ** 2 * currentSplit[-1]) currentCost[-1] += (elem % currentSplit[-1]) * (1 + 2 * (elem // currentSplit[-1])) if currentSplit[-1] != 1: newSplit = currentSplit[-1] - 1 curDecCost = (elem // newSplit) ** 2 * newSplit curDecCost += (elem % newSplit) * (1 + 2 * (elem // newSplit)) heapq.heappush(cost,(curDecCost - currentCost[-1]) * MOD + len(currentCost) - 1) curAns = sum(currentSplit) curCost = sum(currentCost) while curAns > k: curAns -= 1 curElem = heapq.heappop(cost) addedCost = curElem // MOD loc = curElem % MOD currentCost[loc] += addedCost curCost += addedCost currentSplit[loc] -= 1 if currentSplit[loc] != 1: newSplit = currentSplit[loc] - 1 elem = a[loc] curDecCost = (elem // newSplit) ** 2 * newSplit curDecCost += (elem % newSplit) * (1 + 2 * (elem // newSplit)) heapq.heappush(cost,(curDecCost - currentCost[loc]) * MOD + loc) print(curCost) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
104,643
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` from heapq import heappush, heappop def f(length, n_piece): width = length // n_piece extra = length - width * n_piece return width ** 2 * (n_piece - extra) + (width + 1) ** 2 * extra def solve(): N, K = map(int, input().split()) A = [int(x) for x in input().split()] ans = sum(a ** 2 for a in A) heap = [] for i, a in enumerate(A): decrease = f(a, 2) - f(a, 1) n_piece = 2 heappush(heap, (decrease, a, n_piece)) for _ in range(K - N): decrease, a, n_piece = heappop(heap) ans += decrease decrease = f(a, n_piece + 1) - f(a, n_piece) n_piece = n_piece + 1 heappush(heap, (decrease, a, n_piece)) return ans print(solve()) # import matplotlib.pyplot as plt # fig, ax = plt.subplots() # xs = list(range(1, 30)) # ys = [f(25, x) for x in xs] # ax.plot(xs, ys, '.-') # ax.set_xlabel('#piece') # ax.set_ylabel('f(25, x)') # plt.show() ```
104,644
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Submitted Solution: ``` import heapq def value(l,parts): len1 = l//parts len2 = len1+1 cnt2 = l%parts cnt1 = parts-cnt2 return cnt1*len1*len1 + cnt2*len2*len2 def solve(n,k,a): total = 0 pq = [] for i in range(n): total += a[i]*a[i] heapq.heappush(pq,(-1*value(a[i],1)+value(a[i],2),a[i],2)) for i in range(k-n): temp = heapq.heappop(pq) total += temp[0] a,b = temp[1],temp[2] heapq.heappush(pq,(-value(a,b)+value(a,b+1),a,b+1)) return total n,k = map(int,input().split()) a = list(map(int,input().split())) print(solve(n,k,a)) ``` Yes
104,645
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Submitted Solution: ``` from heapq import * def find_add(a, k): extra = a%k return (k-extra)*((a//k)**2) + extra*((1+(a//k))**2) n, mx = map(int, input().split()) lst = list(map(int, input().split())) a = [] heapify(a) for i in lst: heappush(a, (find_add(i, 2)-find_add(i, 1), i, 1)) total = n while total != mx: curr_cont, el, k = heappop(a) new = (find_add(el, k+2)-find_add(el, k+1), el, k+1) heappush(a, new) total += 1 sc = 0 while a: curr_cont, el, k = heappop(a) sc += find_add(el, k) print(sc) ``` Yes
104,646
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Submitted Solution: ``` import sys import bisect as bi import collections as cc import heapq as hp input=sys.stdin.readline I=lambda:list(map(int,input().split())) def ch(n,k): temp=n//k still=n%k ans=(k-still)*((temp)**2)+still*((temp+1)**2) return ans n,k=I() l=I() ans=0 heap=[] for i in range(n): ans+=l[i]**2 hp.heappush(heap,(-ch(l[i],1)+ch(l[i],2),l[i],2)) for i in range(abs(n-k)): now=hp.heappop(heap) ans+=now[0] x,y=now[1],now[2] hp.heappush(heap,(-ch(x,y)+ch(x,y+1),x,y+1)) print(ans) ``` Yes
104,647
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Submitted Solution: ``` import sys from heapq import * sys.setrecursionlimit(10 ** 7) input = sys.stdin.readline f_inf = float('inf') mod = 10 ** 9 + 7 def resolve(): def val(l, nums): unit = l // nums extra = l - unit * nums return (nums - extra) * pow(unit, 2) + extra * pow(unit + 1, 2) n, k = map(int, input().split()) A = list(map(int, input().split())) pq = [] res = 0 for i in range(n): res += pow(A[i], 2) heappush(pq, (-val(A[i], 1) + val(A[i], 2), A[i], 2)) for _ in range(k - n): temp = heappop(pq) res += temp[0] a, b = temp[1], temp[2] heappush(pq, (-val(a, b) + val(a, b + 1), a, b + 1)) print(res) if __name__ == '__main__': resolve() ``` Yes
104,648
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Submitted Solution: ``` n = list(map(int, input().split())) dem=0 output=0 trungbinh=0 sum=0 la=0 a = list(map(int, input().split())) a.sort() for i in range(n[0]): sum+=a[i] dem+=1 trungbinh=sum/n[1] for i in range(n[0]): for j in range(n[1]): if (a[la]<=trungbinh): output+=a[la]*a[la] sum-=a[la] la+=1 else: break trungbinh=sum/(n[1]-la) for i in range(n[0]-la): if(n[1]-la>0): k=a[n[0]-i-1]/trungbinh if (k>=k//1+0.5): k=(k+1)//1 else: k=k//1 la+=k m=a[n[0]-i-1]%k tb=a[n[0]-i-1]//k output+=tb*tb*(k-m)+(tb+1)*(tb+1)*m output=int(output) print(output) ``` No
104,649
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Submitted Solution: ``` for _ in range(1): # n=(int)(input()) # l=list(map(int,input().split())) n,k=map(int,input().split()) l=list(map(int,input().split())) while(len(l)<k): l.sort(reverse=True) l.append(l[0]//2) if l[0]%2==0: l.append(l[0]//2) else: l.append((l[0]//2)+1) l.pop(0) # print(*l) sum=0 # print(l) for i in range(len(l)): sum+=(l[i]*l[i]) print(sum) ``` No
104,650
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Submitted Solution: ``` import collections import heapq as h n,k=map(int,input().split()) nums=list(map(int,input().split())) for i in range(n): nums[i]*=-1 while len(nums)<k: val=h.heappop(nums) val*=-1 v1=val//2 v2=val-v1 h.heappush(nums,-v1) h.heappush(nums,-v2) out=0 for i in nums: out+=i**2 print(out) ``` No
104,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91. Submitted Solution: ``` from math import modf n,k = map(int,input().split()) a = [*map(int,input().split())] s = sum(a) sumdec = 0 res1 = [0 for i in range(k)] for i in range(k): deca = list(i for i in modf(s/k)) res1[i] = int(deca[1]) sumdec += deca[0] if(n==666): print(s) print(sumdec) sumdec = round(sumdec) p = sumdec//k for i in range(k): res1[i] += p for i in range(sumdec%k): res1[i] +=1 res = sum(i**2 for i in res1) print(res) #1109481843390 ``` No
104,652
Provide tags and a correct Python 3 solution for this coding contest problem. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Tags: constructive algorithms, games Correct Solution: ``` from sys import stdin, gettrace if gettrace(): inputi = input else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def solve(): n,m = map(int, inputi().split()) aa = [[int(a) for a in inputi().split()] for _ in range(n)] xor = [0] * (n+m) for i in range(n): for j in range(m): xor[i+j] ^= aa[i][j] if any(x != 0 for x in xor): print("Ashish") else: print("Jeel") def main(): t = int(inputi()) for _ in range(t): solve() if __name__ == "__main__": main() ```
104,653
Provide tags and a correct Python 3 solution for this coding contest problem. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Tags: constructive algorithms, games Correct Solution: ``` def solve_case(): n, m = [int(x) for x in input().split()] a = [[int(x) for x in input().split()] for x in range(n)] xr = [0] * (n + m) for i in range(n): for j in range(m): xr[i + j] ^= a[i][j] return sum(xr) > 0 def main(): for _ in range(int(input())): print(['Jeel', 'Ashish'][solve_case()]) main() ```
104,654
Provide tags and a correct Python 3 solution for this coding contest problem. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Tags: constructive algorithms, games Correct Solution: ``` def solve_case(): n, m = [int(x) for x in input().split()];a = [[int(x) for x in input().split()] for x in range(n)];xr = [0] * (n + m) for i in range(n): for j in range(m):xr[i + j] ^= a[i][j] return sum(xr) > 0 for _ in range(int(input())):print(['Jeel', 'Ashish'][solve_case()]) ```
104,655
Provide tags and a correct Python 3 solution for this coding contest problem. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Tags: constructive algorithms, games Correct Solution: ``` def solve(): n, m = [int(x) for x in input().split()] a = [] for i in range(n): v =[int(x) for x in input().split()] a.append(v) xorsums = [0] * (n+m-1) for i in range(n): for j in range(m): xorsums[i+j] ^= a[i][j] f = 0 for i in range(n+m-1): if xorsums[i] !=0: f = 1 if f == 1: print('Ashish') else: print('Jeel') def main(): t = int(input()) for i in range(t): solve() main() ```
104,656
Provide tags and a correct Python 3 solution for this coding contest problem. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Tags: constructive algorithms, games Correct Solution: ``` def nullify(n, m, mat): xor = [0 for i in range(n+m-1)] for i in range(n): for j in range(m): xor[i+j] ^= mat[i][j] for i in range(n+m-1): if xor[i]: return "Ashish" return "Jeel" t = int(input()) for i in range(t): mat = [] n, m = map(int, input().split()) for j in range(n): mat.append(list(map(int, input().split()))) print(nullify(n, m, mat)) ```
104,657
Provide tags and a correct Python 3 solution for this coding contest problem. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Tags: constructive algorithms, games Correct Solution: ``` def main(): from sys import stdin #from math import gcd from random import randint, choice, shuffle from functools import lru_cache input = stdin.readline #input = open('in', 'r').readline for _ in range(int(input())): n, m = map(int, input().split()) a = [[*map(int, input().split())] for i in range(n)] x = [0] * (n + m) for i in range(n): for j in range(m): x[i + j] ^= a[i][j] if sum(x) == 0: print('Jeel') else: print('Ashish') main() ```
104,658
Provide tags and a correct Python 3 solution for this coding contest problem. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Tags: constructive algorithms, games Correct Solution: ``` # # author: vongkh # created: Wed Nov 25 2020 # from sys import stdin, stdout # only need for big input def solve(): n, m = list(map(int, input().split())) a = [[0] * m for _ in range(n)] for i in range(n): a[i] = list(map(int, input().split())) #the point is to find a win condition for yourself and #force your oponent to be in the lose condition #the win condition is this problem is a simple implementation #but the proof is math heavy. Please check the official editorial win = False for diagonal in range(n + m - 1): xor = 0 for i in range(diagonal + 1): j = diagonal - i if j >= m or i >= n: continue xor = xor ^ a[i][j] if xor != 0: win = True if win : print("Ashish") else: print("Jeel") def main(): t = 1 t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main() ```
104,659
Provide tags and a correct Python 3 solution for this coding contest problem. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Tags: constructive algorithms, games Correct Solution: ``` from functools import reduce def main(): N=int(input()) for _ in range(N): r,c=map(int,input().split()) M=[list(map(int,input().split())) for _ in range(r)] L=[reduce(lambda x,y:x^y, (M[s-k][k] for k in range(max(s-r+1,0),min(s,c-1)+1))) for s in range(r+c-1)] print("Jeel" if all(x==0 for x in L) else "Ashish") main() ```
104,660
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Submitted Solution: ``` from sys import stdin, gettrace if gettrace(): inputi = input else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def solve(): n,m = map(int, inputi().split()) aa = [[int(a) for a in inputi().split()] for _ in range(n)] for i in range(max(n, m)): xor = 0 for j in range(max(0, i-n+1), min(i+1,m)): xor ^= aa[i-j][j] if xor != 0: print("Ashish") return print("Jeel") def main(): t = int(inputi()) for _ in range(t): solve() if __name__ == "__main__": main() ``` No
104,661
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Submitted Solution: ``` from sys import stdin tt = int(stdin.readline()) for loop in range(tt): n,m = map(int,stdin.readline().split()) a = 0 for i in range(n): tmp = list(map(int,stdin.readline().split())) for j in tmp: a ^= j if a == 0: print ("Jeel") else: print ("Ashish") ``` No
104,662
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Submitted Solution: ``` # # author: vongkh # created: Wed Nov 25 2020 # from sys import stdin, stdout # only need for big input def solve(): n, m = list(map(int, input().split())) a = [[0] * m for _ in range(n)] for i in range(n): a[i] = list(map(int, input().split())) #the point is to find a win condition for yourself and #force your oponent to be in the lose condition #the win condition is this problem is a simple implementation #but the proof is math heavy. Please check the official editorial win = False for diagonal in range(n + m - 1): xor = 0 for i in range(min(n, diagonal+1)): j = diagonal - i if j >= m : break xor = xor ^ a[i][j] if xor != 0: win = True if win : print("Ashish") else: print("Jeel") def main(): t = 1 t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main() ``` No
104,663
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. * Choose a starting cell (r_1, c_1) with non-zero value. * Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2. * Decrease the value of the starting cell by some positive non-zero integer. * Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: * a shortest path is one that passes through the least number of cells; * all cells on this path excluding the starting cell, but the finishing cell may be modified; * the resulting value of each cell must be a non-negative integer; * the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed. The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally. Given the initial matrix, if both players play optimally, can you predict who will win? Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix. The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix. Output For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes). Example Input 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish Note In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner. In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. Submitted Solution: ``` from sys import stdin tt = int(stdin.readline()) for loop in range(tt): n,m = map(int,stdin.readline().split()) lis = [] for i in range(n): tmp = list(map(int,stdin.readline().split())) lis.append(tmp) a = 0 s = 0 for k in range(n+m): for i in range(n): j = k-i if j < 0 or m <= j: continue a ^= lis[i][j] s += lis[i][j] if s > 0: break if a == 0: print ("Jeel") else: print ("Ashish") ``` No
104,664
Provide tags and a correct Python 3 solution for this coding contest problem. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Tags: combinatorics, math, sortings Correct Solution: ``` def cnk_mod(max_n, m): cnk = [[1]] for n in range(1, max_n + 1): tmp = [1] for k in range(1, n): tmp.append((cnk[n - 1][k - 1] + cnk[n - 1][k]) % m) tmp.append(1) cnk.append(tmp) return cnk ''' if k == 0 or k == n: return 1 r = cnk_mod(n - 1, k - 1, m) + cnk_mod(n - 1, k, m) r %= m return r''' M = 10 ** 9 + 7 #print(M) cnk = cnk_mod(1001, M) #print(cnk) tests = int(input()) for t in range(tests): n, k = [int(s) for s in input().split()] a = [int(s) for s in input().split()] a.sort() x = 0 i = n - k - 1 while i >= 0 and a[i] == a[n - k]: x += 1 i -= 1 y = 0 i = n - k while i < n and a[i] == a[n - k]: y += 1 i += 1 #print(a, x, y) print(cnk[x + y][x]) ```
104,665
Provide tags and a correct Python 3 solution for this coding contest problem. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Tags: combinatorics, math, sortings Correct Solution: ``` """ #If FastIO not needed, use this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right import time from types import GeneratorType 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") from collections import defaultdict as dd, deque as dq, Counter as dc import math, string #start_time = time.time() def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def isInt(s): return '0' <= s[0] <= '9' MOD = 10**9 + 7 """ """ facs = [1] curr = 1 for j in range(1,1005): curr *= j curr %= MOD facs.append(curr) inv_facs = [] for f in facs: inv_facs.append(pow(f,MOD-2,MOD)) def ncr(n,k): return (facs[n]*inv_facs[k]*inv_facs[n-k])%MOD def solve(): N, K = getInts() A = getInts() A.sort(reverse=True) ans = 0 ind = K-1 while ind >= 0: if A[ind] == A[K-1]: ind -= 1 else: break ind2 = K-1 while ind2 < N: if A[ind2] == A[K-1]: ind2 += 1 else: break ind2 -= 1 ind += 1 n = ind2-ind+1 k = K-ind return ncr(n,k) for _ in range(getInt()): print(solve()) #solve() #print(time.time()-start_time) ```
104,666
Provide tags and a correct Python 3 solution for this coding contest problem. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Tags: combinatorics, math, sortings Correct Solution: ``` import math,sys input=sys.stdin.readline from collections import Counter def fact(n): res = 1 for i in range(2, n+1): res = res * i return res def nCr(n, r): p=10**9 +7 # initialize numerator # and denominator num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p for _ in range(int(input())): n,k=map(int,input().split()) l=list(map(int,input().split())) l.sort(reverse=True) c=Counter(l) #z=sum(l[:k]) s=1 if c[l[k-1]]>1: s=nCr(c[l[k-1]],k-l.index(l[k-1])) print(int(s)%(10**9+7)) ```
104,667
Provide tags and a correct Python 3 solution for this coding contest problem. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Tags: combinatorics, math, sortings Correct Solution: ``` 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") ########################################################## def nCk(n, k): res = 1 for i in range(1, k + 1): res = res * (n - i + 1) // i return res from collections import Counter for t in range(int(input())): n,k=map(int, input().split()) arr=sorted(list(map(int,input().split())),reverse=True) ans=1 d1=Counter(arr[:k]) d2=Counter(arr[k:]) #print(arr) #print(f[:10]) vis=[0]*1001 for i in range(k): if vis[arr[i]]==0 and d2[arr[i]]>=1: ans*=nCk(d1[arr[i]]+d2[arr[i]],d1[arr[i]]) vis[arr[i]]=1 ans=max(ans,1) print((ans)%(10**9+7)) ```
104,668
Provide tags and a correct Python 3 solution for this coding contest problem. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Tags: combinatorics, math, sortings Correct Solution: ``` mod=10**9+7 def ncr(a,b): c=1 for i in range(a,b,-1): c=(c*i)%mod d=1 for i in range(1,a-b+1): d=(d*i)%mod d=pow(d,mod-2,mod) return (c*d)%mod t=int(input()) for _ in range(t): n,k=map(int,input().split()) l=list(map(int,input().split())) l.sort(reverse=True) d={} for i in range(k): try: d[l[i]]+=1 except: d[l[i]]=1 e={} for i in l: try: e[i]+=1 except: e[i]=1 ans=1 for i in d: ans=ans*ncr(e[i],d[i]) print(ans) ```
104,669
Provide tags and a correct Python 3 solution for this coding contest problem. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Tags: combinatorics, math, sortings Correct Solution: ``` from math import factorial n = int(input()) for k in range(n): a = list(map(int, input().split())) b = list(map(int, input().split())) b.sort() temp = b[a[0]-a[1]:] not_chosen = b[:a[0]-a[1]] if not_chosen.count(b[a[0]-a[1]]) > 0: possible = temp.count(b[a[0]-a[1]]) + not_chosen.count(b[a[0]-a[1]]) need = temp.count(b[a[0]-a[1]]) x = factorial(possible)//factorial(possible - need) y = factorial(need) z = x//y print(z % 1000000007) else: print(1) ```
104,670
Provide tags and a correct Python 3 solution for this coding contest problem. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Tags: combinatorics, math, sortings Correct Solution: ``` from itertools import repeat, groupby def line(): return map(int, input().split()) def num(): return int(input()) def nfunc(f, n, *args, **kwargs): return (f(*args, **kwargs) for _ in repeat(None, n)) t = num() for _ in repeat(None, t): n,k = line() blogs = [len(list(g)) for _,g in groupby(sorted(line())[::-1])] ans = 1 for m in blogs: if k<=m: for i in range(1, k+1): ans *= (m-k+i) for i in range(1, k+1): ans //= i break else: k -= m print(ans % (10**9 + 7)) ```
104,671
Provide tags and a correct Python 3 solution for this coding contest problem. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Tags: combinatorics, math, sortings Correct Solution: ``` import io,os input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline N = 10001 # array to store inverse of 1 to N factorialNumInverse = [None] * (N + 1) # array to precompute inverse of 1! to N! naturalNumInverse = [None] * (N + 1) # array to store factorial of # first N numbers fact = [None] * (N + 1) # Function to precompute inverse of numbers def InverseofNumber(p): naturalNumInverse[0] = naturalNumInverse[1] = 1 for i in range(2, N + 1, 1): naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - int(p / i)) % p) # Function to precompute inverse # of factorials def InverseofFactorial(p): factorialNumInverse[0] = factorialNumInverse[1] = 1 # precompute inverse of natural numbers for i in range(2, N + 1, 1): factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p # Function to calculate factorial of 1 to N def factorial(p): fact[0] = 1 # precompute factorials for i in range(1, N + 1): fact[i] = (fact[i - 1] * i) % p # Function to return nCr % p in O(1) time def Binomial(N, R, p): # n C r = n!*inverse(r!)*inverse((n-r)!) ans = ((fact[N] * factorialNumInverse[R])% p * factorialNumInverse[N - R])% p return ans p = 1000000007 InverseofNumber(p) InverseofFactorial(p) factorial(p) t=int(input()) for _ in range(t): n,k=list(map(int,input().split())) arr=list(map(int,input().split())) arr.sort() c=[0]*n for i in range(n): c[arr[i]-1]+=1 a=[0]*n for i in range(k): a[arr[-i-1]-1]+=1 ans=1 for i in range(n): if a[i]>0: ans*=Binomial(c[i],a[i],p) ans%=p print(ans) ```
104,672
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Submitted Solution: ``` import math import sys input=sys.stdin.readline from collections import Counter, defaultdict, deque MAX_N = 1007 MOD = 10**9 + 7 def modInverse(a, p): # Fermat's little theorem, a**(p-1) = 1 mod p # assert a % p != 0 return pow(a, p - 2, p) # Precompute all factorials: i! fact = [1] for i in range(1, MAX_N + 1): fact.append((fact[-1] * i) % MOD) # Precompute all inverse factorials: 1 / (i!) invFact = [0] * (MAX_N + 1) invFact[MAX_N] = modInverse(fact[MAX_N], MOD) for i in range(MAX_N - 1, -1, -1): invFact[i] = (invFact[i + 1] * (i + 1)) % MOD # assert fact[i] * invFact[i] % MOD == 1 # Precompute all inverses, 1 / i == (i - 1)! / i! inv = [0] * (MAX_N + 1) for i in range(1, MAX_N + 1): inv[i] = fact[i - 1] * invFact[i] % MOD # assert inv[i] * i % MOD == 1 def nCr(n, r): # mod'd if n < r: return 0 return (fact[n] * invFact[r] * invFact[n - r]) % MOD def f(n, k, a): l = list(set(a)) l.sort(reverse=True) c = Counter(a) el = 0 for i in range(len(l)): el += c[l[i]] if el >= k: el -= c[l[i]] last = i break r = l[last] co = c[r] #print(r, co, el) return nCr(co, k - el) t = int(input()) result = [] for i in range(t): #n = int(input()) n, k = list(map(int, input().split())) a = list(map(int, input().split())) result.append(f(n, k, a)) for i in range(t): print(result[i]) ``` Yes
104,673
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Submitted Solution: ``` from collections import Counter T = int(input()) ans_ls = [0] * T class Combination(): def __init__(self, n, mod=10**9+7): self.mod = mod self.fac = [1]*(n+1) for i in range(1,n+1): self.fac[i] = self.fac[i-1] * i % self.mod self.invfac = [1]*(n+1) self.invfac[n] = pow(self.fac[n], self.mod - 2, self.mod) for i in range(n-1, 0, -1): self.invfac[i] = self.invfac[i+1] * (i+1) % self.mod def nCr(self, n, r, default_none = 0): if n < r: return default_none return self.fac[n] * self.invfac[r] % self.mod * self.invfac[n-r] % self.mod def permutation(self, n, r, default_none = 0): if n < r: return default_none return self.factorial(n) * self.invfactorial(n-r) % self.mod def factorial(self, i): return self.fac[i] def invfactorial(self, i): return self.invfac[i] c = Combination(10**3+10) for t in range(T): N,K = map(int,input().split()) a_ls = list(map(int, input().split())) a_ls.sort(reverse=True) selected = a_ls[:K] best_min = selected[-1] best_notmin_count = 0 for i in range(K): if a_ls[i] != best_min: best_notmin_count += 1 min_count_in_total = Counter(a_ls)[best_min] ans_ls[t] = c.nCr(min_count_in_total, K - best_notmin_count) for ans in ans_ls: print(ans) ``` Yes
104,674
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Submitted Solution: ``` from collections import Counter mod = 1000000007 factorials = [1] for i in range(1, 1000001): factorials.append((factorials[-1] * i) % mod) t = int(input()) for _ in range(t): n, k = map(int, input().split()) A = list(map(int, input().split())) A.sort(reverse = True) CA = Counter(A) first_k = A[:k] Ck = Counter(first_k) ans = 1 for x in Ck: n, r = CA[x], Ck[x] fn, fr, fnr = factorials[n], factorials[r], factorials[n - r] ncr = (fn * pow(fr*fnr, mod - 2, mod)) % mod ans = (ans * ncr) % mod print(ans) ``` Yes
104,675
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Submitted Solution: ``` import math from collections import Counter def nCr(n,r): f = math.factorial return f(n) // f(r) // f(n-r) for _ in range(int(input())): n,k = map(int,input().split()) l = list(map(int,input().split())) d = Counter(l) l.sort(reverse = 1) ans = 1 a = l[k-1] i = k-1 c = 0 while i>-1: if l[i] == a: c+=1 else: break i-=1 x = nCr(d[a],c) print(x%(10**9 + 7)) ``` Yes
104,676
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Submitted Solution: ``` for _ in range(int(input())): n, k = map(int, input().split()) a = list(map(int, input().split())) # n bloggers result = 1 if n > k: d = {} s = set() for i in a: if i not in d: d[i] = 1 s.add(i) else: d[i] += 1 s = sorted(list(s)) s.reverse() for i in s: if k <= 0: break if d[i] <= k: k -= d[i] else: n = d[i] result1 = 1 if 2*k > n: k = n-k for j in range(n, k, -1): result *= j result1 *= n+1-j result = round(result/result1) break print(result % (10**9+7)) ``` No
104,677
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Submitted Solution: ``` import math for _ in range(int(input())): n,k = map(int,input().split()) a = list(map(int,input().split())) a.sort(reverse=True) t = a.count(a[k-1]) s = 0 j = k-1 while a[j] == a[k-1] and j>=0: s += 1 j -= 1 if len(set(a)) == 1: s = k t = n print(math.factorial(t)//(math.factorial(t-s)*math.factorial(s))) ``` No
104,678
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Submitted Solution: ``` from math import * from sys import * from bisect import * from collections import * def fact(x): a=1 for i in range(1,x+1): a*=i return a def solve(n,k): x=fact(n) y=fact(k) z=fact(n-k) return x//(y*z) t=int(stdin.readline()) for _ in range(t): n,k=map(int,stdin.readline().split()) a=list(map(int,stdin.readline().split())) a.sort() a=a[::-1] d={} b=[] for i in range(n): if a[i] not in d: d[a[i]]=0 b.append(a[i]) d[a[i]]+=1 f=0 j=0 for i in range(len(b)): k -= d[b[i]] if k<0: f=1 j=i k+=d[b[i]] break if k==0: break if f==1: ans=solve(d[b[j]],k) print(ans) else: print(1) ``` No
104,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select k bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if n=4, k=3, a=[1, 3, 1, 2], then Masha has two ways to select 3 bloggers with the maximum total number of followers: * conclude contracts with bloggers with numbers 1, 2 and 4. In this case, the number of followers will be equal to a_1 + a_2 + a_4 = 6. * conclude contracts with bloggers with numbers 2, 3 and 4. In this case, the number of followers will be equal to a_2 + a_3 + a_4 = 6. Since the answer can be quite large, output it modulo 10^9+7. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains n integers a_1, a_2, … a_n (1 ≤ a_i ≤ n) — the number of followers of each blogger. It is guaranteed that the sum of n over all test cases does not exceed 1000. Output For each test case, on a separate line output one integer — the number of ways to select k bloggers so that the total number of their followers is maximum possible. Example Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 Note The test case is explained in the statements. In the second test case, the following ways are valid: * conclude contracts with bloggers with numbers 1 and 2. In this case, the number of followers will be equal to a_1 + a_2 = 2; * conclude contracts with bloggers with numbers 1 and 3. In this case, the number of followers will be equal to a_1 + a_3 = 2; * conclude contracts with bloggers with numbers 1 and 4. In this case, the number of followers will be equal to a_1 + a_4 = 2; * conclude contracts with bloggers with numbers 2 and 3. In this case, the number of followers will be equal to a_2 + a_3 = 2; * conclude contracts with bloggers with numbers 2 and 4. In this case, the number of followers will be equal to a_2 + a_4 = 2; * conclude contracts with bloggers with numbers 3 and 4. In this case, the number of followers will be equal to a_3 + a_4 = 2. In the third test case, the following ways are valid: * concludes a contract with a blogger with the number 2. In this case, the number of followers will be equal to a_2 = 2. Submitted Solution: ``` from sys import stdin #import math input = stdin.readline def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p tc = int(input()) for _ in range(tc): n,k = map(int,input().split()) a=list(map(int,input().split())) a.sort(reverse=True) d = {} y=a.count(a[k-1]) a = a[:k] x=a.count(a[-1]) print(ncr(y, x, 1000000009)) ``` No
104,680
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two tables A and B of size n × m. We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, their relative order does not change (such sorting algorithms are called stable). You can find this behavior of sorting by column in many office software for managing spreadsheets. Petya works in one, and he has a table A opened right now. He wants to perform zero of more sortings by column to transform this table to table B. Determine if it is possible to do so, and if yes, find a sequence of columns to sort by. Note that you do not need to minimize the number of sortings. Input The first line contains two integers n and m (1 ≤ n, m ≤ 1500) — the sizes of the tables. Each of the next n lines contains m integers a_{i,j} (1 ≤ a_{i, j} ≤ n), denoting the elements of the table A. Each of the next n lines contains m integers b_{i, j} (1 ≤ b_{i, j} ≤ n), denoting the elements of the table B. Output If it is not possible to transform A into B, print -1. Otherwise, first print an integer k (0 ≤ k ≤ 5000) — the number of sortings in your solution. Then print k integers c_1, …, c_k (1 ≤ c_i ≤ m) — the columns, by which Petya needs to perform a sorting. We can show that if a solution exists, there is one in no more than 5000 sortings. Examples Input 2 2 2 2 1 2 1 2 2 2 Output 1 1 Input 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 Output 2 1 2 Input 2 2 1 1 2 1 2 1 1 1 Output -1 Input 4 1 2 2 2 1 1 2 2 2 Output 1 1 Note Consider the second example. After the sorting by the first column the table becomes $$$\begin{matrix} 1&3&3\\\ 1&1&2\\\ 2&3&2. \end{matrix}$$$ After the sorting by the second column the table becomes $$$\begin{matrix} 1&1&2\\\ 1&3&3\\\ 2&3&2, \end{matrix}$$$ and this is what we need. In the third test any sorting does not change anything, because the columns are already sorted. Submitted Solution: ``` def check(a,b): for i in range(len(a)): if(a[i]!=b[i]): return(False) return(True) def sort(a): if(len(a)<=1): return(a) else: pivot=a.pop() left=[] right=[] for i in a: if(i<pivot): left.append(i) else: right.append(i) return(sort(left)+[pivot]+sort(right)) a,b=map(int,input().split()) c=[] d=[] count=0 z=0 out=[] for i in range(a): x=[int(x) for x in input().split()] c.append(x) for j in range(a): x=[int(x) for x in input().split()] d.append(x) for i in range(b): fi=[] sec=[] ram=0 for j in range(a): fi.append(c[j][i]) sec.append(d[j][i]) if(not(check(fi,sec))): fi=sort(fi) ram=1 if(ram==1): if(check(fi,sec)): count+=1 out.append(i+1) else: z=1 break if(z==0): print(count) print(*out,sep=" ") else: print(-1) ``` No
104,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two tables A and B of size n × m. We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, their relative order does not change (such sorting algorithms are called stable). You can find this behavior of sorting by column in many office software for managing spreadsheets. Petya works in one, and he has a table A opened right now. He wants to perform zero of more sortings by column to transform this table to table B. Determine if it is possible to do so, and if yes, find a sequence of columns to sort by. Note that you do not need to minimize the number of sortings. Input The first line contains two integers n and m (1 ≤ n, m ≤ 1500) — the sizes of the tables. Each of the next n lines contains m integers a_{i,j} (1 ≤ a_{i, j} ≤ n), denoting the elements of the table A. Each of the next n lines contains m integers b_{i, j} (1 ≤ b_{i, j} ≤ n), denoting the elements of the table B. Output If it is not possible to transform A into B, print -1. Otherwise, first print an integer k (0 ≤ k ≤ 5000) — the number of sortings in your solution. Then print k integers c_1, …, c_k (1 ≤ c_i ≤ m) — the columns, by which Petya needs to perform a sorting. We can show that if a solution exists, there is one in no more than 5000 sortings. Examples Input 2 2 2 2 1 2 1 2 2 2 Output 1 1 Input 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 Output 2 1 2 Input 2 2 1 1 2 1 2 1 1 1 Output -1 Input 4 1 2 2 2 1 1 2 2 2 Output 1 1 Note Consider the second example. After the sorting by the first column the table becomes $$$\begin{matrix} 1&3&3\\\ 1&1&2\\\ 2&3&2. \end{matrix}$$$ After the sorting by the second column the table becomes $$$\begin{matrix} 1&1&2\\\ 1&3&3\\\ 2&3&2, \end{matrix}$$$ and this is what we need. In the third test any sorting does not change anything, because the columns are already sorted. Submitted Solution: ``` # C. Matrix Sorting: https://codeforces.com/contest/1500/problem/C # glob_x = """ # 2 2 2 1 # 2 2 1 2 # 1 2 2 2 # 2 1 2 2 # 2 2 1 2 # 2 1 2 2 # 1 2 2 2 # 2 2 2 1 # """ # def get_ab(glob_x): # glob_x = glob_x[1:-1].split('\n') # n = len(glob_x) // 2 # a, b = [], [] # for i in range(n): # a.append(glob_x[i].split(' ')) # for i in range(n, 2 * n): # b.append(glob_x[i].split(' ')) # m = len(a[0]) # return n, m, a, b # print(get_ab(glob_x)) def main(): n, m = list(map(lambda x: int(x), str(input()).split(' '))) u = {} states = {} end = '' a, b = [], [] for i in range(n): t = input() a.append(t.split(' ')) if t not in u: u[t] = 1 else: u[t] += 1 for i in range(n): t = input() b.append(t.split(' ')) if t not in u: print(-1) return else: u[t] -= 1 if u[t] == 0: del u[t] # n, m, a, b = get_ab(glob_x) end = get_str(b) s = [] ans = bt(a, s, end, states) if not ans: print(-1) return def is_solved(a, s, end): if len(s) > 5000: return False if get_str(a) == end: return True return False def get_str(a): return '$'.join(map(lambda x: ' '.join(x), a)) def bt(a, s, end, states): # print(len(states), states, '\n') if is_solved(a, s, end): print(len(s)) print(' '.join(map(lambda x: str(x), s))) return True for i in range(len(a[0])): # print('#' * len(s) + str(i)) if len(s) == 0: s.append(4) else: s.append(i + 1) new_a = sort(a, i + 1) new_str = get_str(new_a) added = False if not new_str in states: states[new_str] = True added = True if bt(new_a, s, end, states): return True if added: del states[new_str] s.pop() # print("-" * 20) return False def sort(a, i): return sorted(a, key=lambda x: x[i - 1]) if __name__ == "__main__": main() ``` No
104,682
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two tables A and B of size n × m. We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, their relative order does not change (such sorting algorithms are called stable). You can find this behavior of sorting by column in many office software for managing spreadsheets. Petya works in one, and he has a table A opened right now. He wants to perform zero of more sortings by column to transform this table to table B. Determine if it is possible to do so, and if yes, find a sequence of columns to sort by. Note that you do not need to minimize the number of sortings. Input The first line contains two integers n and m (1 ≤ n, m ≤ 1500) — the sizes of the tables. Each of the next n lines contains m integers a_{i,j} (1 ≤ a_{i, j} ≤ n), denoting the elements of the table A. Each of the next n lines contains m integers b_{i, j} (1 ≤ b_{i, j} ≤ n), denoting the elements of the table B. Output If it is not possible to transform A into B, print -1. Otherwise, first print an integer k (0 ≤ k ≤ 5000) — the number of sortings in your solution. Then print k integers c_1, …, c_k (1 ≤ c_i ≤ m) — the columns, by which Petya needs to perform a sorting. We can show that if a solution exists, there is one in no more than 5000 sortings. Examples Input 2 2 2 2 1 2 1 2 2 2 Output 1 1 Input 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 Output 2 1 2 Input 2 2 1 1 2 1 2 1 1 1 Output -1 Input 4 1 2 2 2 1 1 2 2 2 Output 1 1 Note Consider the second example. After the sorting by the first column the table becomes $$$\begin{matrix} 1&3&3\\\ 1&1&2\\\ 2&3&2. \end{matrix}$$$ After the sorting by the second column the table becomes $$$\begin{matrix} 1&1&2\\\ 1&3&3\\\ 2&3&2, \end{matrix}$$$ and this is what we need. In the third test any sorting does not change anything, because the columns are already sorted. Submitted Solution: ``` l,c=map(int, input().split()) A=list() nA=list() B=list() tb=list() cpt=0 i=0 for s in range(l*2): if s<l: A.append(list(map(int,input().split()))[:c]) elif s>=l: B.append(list(map(int, input().split()))[:c]) if A == B: cpt=c nA=[x+1 for x in range(c)] else: while i <c: tem = list() for index,z in enumerate(A): tem.append((z[i],index)) for ind,z in enumerate(B): tb.append((z[i],ind)) stem=sorted(tem, key= lambda x:x[0]) if tem !=stem: cpt+=1 nA.append(i+1) for w in range(len(stem)): u=stem[w][1] A[w][i:]=A[u][i:] i+=1 print(cpt) if cpt>0 else print(-1) print(' '.join(str(z) for z in nA)) if cpt>0 else print('') ``` No
104,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two tables A and B of size n × m. We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, their relative order does not change (such sorting algorithms are called stable). You can find this behavior of sorting by column in many office software for managing spreadsheets. Petya works in one, and he has a table A opened right now. He wants to perform zero of more sortings by column to transform this table to table B. Determine if it is possible to do so, and if yes, find a sequence of columns to sort by. Note that you do not need to minimize the number of sortings. Input The first line contains two integers n and m (1 ≤ n, m ≤ 1500) — the sizes of the tables. Each of the next n lines contains m integers a_{i,j} (1 ≤ a_{i, j} ≤ n), denoting the elements of the table A. Each of the next n lines contains m integers b_{i, j} (1 ≤ b_{i, j} ≤ n), denoting the elements of the table B. Output If it is not possible to transform A into B, print -1. Otherwise, first print an integer k (0 ≤ k ≤ 5000) — the number of sortings in your solution. Then print k integers c_1, …, c_k (1 ≤ c_i ≤ m) — the columns, by which Petya needs to perform a sorting. We can show that if a solution exists, there is one in no more than 5000 sortings. Examples Input 2 2 2 2 1 2 1 2 2 2 Output 1 1 Input 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 Output 2 1 2 Input 2 2 1 1 2 1 2 1 1 1 Output -1 Input 4 1 2 2 2 1 1 2 2 2 Output 1 1 Note Consider the second example. After the sorting by the first column the table becomes $$$\begin{matrix} 1&3&3\\\ 1&1&2\\\ 2&3&2. \end{matrix}$$$ After the sorting by the second column the table becomes $$$\begin{matrix} 1&1&2\\\ 1&3&3\\\ 2&3&2, \end{matrix}$$$ and this is what we need. In the third test any sorting does not change anything, because the columns are already sorted. Submitted Solution: ``` rows, columns = map(int, input().split()) table1 = [] table2 = [] for i in range(rows): table1 += [list(map(int, input().split()))] for i in range(rows): table2 += [list(map(int, input().split()))] sorts = [] f = True for i in range(columns): column1 = [] column2 = [] for j in range(rows): column1 += [table1[j][i]] column2 += [table2[j][i]] if column1 == column2: break else: column1.sort() if column1 == column2: column2.sort() if column1 == column2: sorts += [i + 1] else: f = False else: f = False if f: print(len(sorts)) for i in sorts: print(i, end=' ') else: print(-1) ``` No
104,684
Provide tags and a correct Python 3 solution for this coding contest problem. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Tags: combinatorics, dp, math, probabilities, two pointers Correct Solution: ``` p=998244353 def f(x,y): r=1 x=x%p if x==0: return 0 while y>0: if y%2==1: r=(r*x)%p y=y>>1 x=(x*x)%p return r n,m=map(int,input().split()) l=[] for _ in range(n): l.append(list(map(int,input().split()))) a=1 for i in range(1,n+1): a=(a*i)%p q=0 for i in range(m): v=[0]*n for j in range(n): v[j]=l[j][i] v.sort() x=1 for j in range(n): x=(x*(min(v[j]-1,n)-j))%p q=(q+a-x)%p print((q*f(a,p-2))%p) ```
104,685
Provide tags and a correct Python 3 solution for this coding contest problem. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Tags: combinatorics, dp, math, probabilities, two pointers Correct Solution: ``` ans = 0 n,m = map(int,input().split()) mod = 998244353 a = [list(map(int,input().split())) for i in range(n)] fac = 1 for i in range(1,n+1): fac *= i inv = pow(fac,mod-2,mod) for j in range(m): na = sorted([a[i][j] for i in range(n)]) now = 1 able = 0 for i in range(n): while len(na) > 0 and na[-1] > n-i: del na[-1] able += 1 now *= able able -= 1 ans += now * inv ans %= mod print ((m-ans) % mod) ```
104,686
Provide tags and a correct Python 3 solution for this coding contest problem. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Tags: combinatorics, dp, math, probabilities, two pointers Correct Solution: ``` n, m = map(int, input().split()) mod = 998244353 dis = [[0]*(m+1) for i in range(n+1)] # dis = [[1,4,4,3,4], [1,4,1,4,2], [1,4,4,4,3]] jc = 1 ans = 0 def ksm(a, b, p): a = a%p b = b%(p-1) cheng = a ret = 1 while b>0: if b%2: ret = ret*cheng%p cheng = cheng*cheng%p b //= 2 return ret def inv(a, p=mod): return ksm(a, p-2, p) for i in range(n): jc = jc*(i+1)%mod for i in range(n): t = list(map(int, input().split())) for j in range(m): dis[i][j] = t[j] for i in range(m): c = [0]*(n) for j in range(n): c[j] = dis[j][i] - 1 c.sort() ret = 1 for index, j in enumerate(c): ret = ret * max(0, j-index) ret = ret*inv(jc)%mod ret = ((1 - ret)%mod + mod)%mod ans = (ans + ret)%mod print(ans) ```
104,687
Provide tags and a correct Python 3 solution for this coding contest problem. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Tags: combinatorics, dp, math, probabilities, two pointers Correct Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r 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.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 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): if r==self.size: r = self.num 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 def cmb(n, r, mod): if ( r<0 or r>n ): return 0 r = min(r, n-r) return g1[n] * g2[r] * g2[n-r] % mod mod = 998244353 N = 100 g1 = [1]*(N+1) g2 = [1]*(N+1) inverse = [1]*(N+1) for i in range( 2, N + 1 ): g1[i]=( ( g1[i-1] * i ) % mod ) inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod ) g2[i]=( (g2[i-1] * inverse[i]) % mod ) inverse[0]=0 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log input = lambda :sys.stdin.buffer.readline() mi = lambda :map(int,input().split()) li = lambda :list(mi()) n,m = mi() d = [li() for i in range(n)] res = m for i in range(m): cnt = [0 for j in range(n)] flag = True for j in range(n): if d[j][i]==1: flag = False break else: cnt[d[j][i]-2] += 1 if not flag: continue tmp = 1 rest = 0 for j in range(n): rest += 1 for k in range(cnt[j]): tmp *= rest tmp %= mod rest -= 1 res -= tmp * g2[n] res %= mod print(res) ```
104,688
Provide tags and a correct Python 3 solution for this coding contest problem. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Tags: combinatorics, dp, math, probabilities, two pointers Correct Solution: ``` import sys from sys import stdin ans = 0 n,m = map(int,stdin.readline().split()) mod = 998244353 a = [list(map(int,stdin.readline().split())) for i in range(n)] fac = 1 for i in range(1,n+1): fac *= i inv = pow(fac,mod-2,mod) for j in range(m): na = [a[i][j] for i in range(n)] na.sort() now = 1 able = 0 for i in range(n): while len(na) > 0 and na[-1] > n-i: del na[-1] able += 1 now *= able able -= 1 ans += now * inv ans %= mod #print (ans) print ((m-ans) % mod) ```
104,689
Provide tags and a correct Python 3 solution for this coding contest problem. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Tags: combinatorics, dp, math, probabilities, two pointers Correct Solution: ``` from bisect import bisect,bisect_left from collections import * from heapq import * from math import gcd,ceil,sqrt,floor,inf from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ 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 A(n):return [0]*n def AI(n,x): return [x]*n def A2(n,m): return [[0]*m for i in range(n)] def G(n): return [[] for i in range(n)] def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc mod=10**9+7 farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1)) if a==0:return b//c*(n+1) if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2 m=(a*n+b)//c return n*m-floorsum(c,c-b-1,a,m-1) def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class ST: def __init__(self,arr):#n!=0 n=len(arr) mx=n.bit_length()#取不到 self.st=[[0]*mx for i in range(n)] for i in range(n): self.st[i][0]=arr[i] for j in range(1,mx): for i in range(n-(1<<j)+1): self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1]) def query(self,l,r): if l>r:return -inf s=(r+1-l).bit_length()-1 return max(self.st[l][s],self.st[r-(1<<s)+1][s]) class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv class UF:#秩+路径+容量,边数 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n self.size=AI(n,1) self.edge=A(n) def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: self.edge[pu]+=1 return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu self.edge[pu]+=self.edge[pv]+1 self.size[pu]+=self.size[pv] if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv self.edge[pv]+=self.edge[pu]+1 self.size[pv]+=self.size[pu] def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d=AI(n,inf) d[s]=0 heap=[(0,s)] vis=A(n) while heap: dis,u=heappop(heap) if vis[u]: continue vis[u]=1 for v,w in graph[u]: if d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def bell(s,g):#bellman-Ford dis=AI(n,inf) dis[s]=0 for i in range(n-1): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change=A(n) for i in range(n): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change[v]=1 return dis def lcm(a,b): return a*b//gcd(a,b) def lis(nums): res=[] for k in nums: i=bisect.bisect_left(res,k) if i==len(res): res.append(k) else: res[i]=k return len(res) def RP(nums):#逆序对 n = len(nums) s=set(nums) d={} for i,k in enumerate(sorted(s),1): d[k]=i bi=BIT([0]*(len(s)+1)) ans=0 for i in range(n-1,-1,-1): ans+=bi.query(d[nums[i]]-1) bi.update(d[nums[i]],1) return ans class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j,n,m): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj def topo(n): q=deque() res=[] for i in range(1,n+1): if ind[i]==0: q.append(i) res.append(i) while q: u=q.popleft() for v in g[u]: ind[v]-=1 if ind[v]==0: q.append(v) res.append(v) return res @bootstrap def gdfs(r,p): for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None @bootstrap def dfs(r,p): for ch,w in g[r]: if ch!=p: res[ch]=res[r]^w yield dfs(ch,r) yield None #from random import randint t=1 mod=998244353 for i in range(t): n,m=RL() d=[] for i in range(n): d.append(RLL()) ifact(n,mod) ans=0 for j in range(m): res=[] for i in range(n): ma=d[i][j]-1 res.append(ma) res.sort() tmp=1 for i,v in enumerate(res): if v<=i: tmp=0 break else: tmp=tmp*(v-i)%mod ans+=(1-tmp*ifa[n]%mod) ans%=mod print(ans) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thr ead(target=main) t.start() t.join() ''' ```
104,690
Provide tags and a correct Python 3 solution for this coding contest problem. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Tags: combinatorics, dp, math, probabilities, two pointers Correct Solution: ``` from sys import stdin mod = 998244353 n,m=map(int,input().split()) arr=[] for i in range(m): arr.append([]) for i in range(n): temp=list(map(int,stdin.readline().split())) for j in range(m): arr[j].append(temp[j]) for i in range(m): arr[i].sort() ans=1 for i in range(1,n+1): ans*=i den=ans ans*=m ans%=mod for i in range(m): temp=1 for j in range(n): temp*=arr[i][j]-(j+1) ans -= temp ans%=mod ans *= pow(den,mod-2,mod) ans%=mod print(ans) ```
104,691
Provide tags and a correct Python 3 solution for this coding contest problem. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Tags: combinatorics, dp, math, probabilities, two pointers Correct Solution: ``` def get_one(ns,m): n=len(ns) ans=1 for i in range(n): t=ns[i]-i if t<=0: return 0 ans=ans*t%m return ans def get_one_pre(ns:list): ans=[0]*len(ns) ns.sort() l=0 for i in range(len(ns)): for j in range(l,len(ns)): if i+1<ns[j]: l = j ans[i] = len(ns) - l break else: l=j ans[i]=0 return list(reversed(ans)) def pow(a,b,m): tb=[a] for i in range(35): tb.append(tb[-1]*tb[-1]%m) ans=1 for i in range(35): if (b>>i)&1==1: ans=ans*tb[i]%m return ans def inv(a,m): return pow(a,m-2,m) def functoria(x,m): ans=1 for i in range(1,x+1): ans=ans*i%m return ans def gns(): return list(map(int,input().split())) def gn(): return int(input()) n,m=gns() md=998244353 ms=[[]for i in range(m)] for i in range(n): ns=gns() for i in range(m): ms[i].append(ns[i]) sm=0 for i in range(m): x=get_one_pre(ms[i]) y=get_one(x,md) sm=(sm+y)%md f=functoria(n,md) fv=inv(f,md) ans=(f*m-sm+md)*fv%md print(ans) ```
104,692
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Submitted Solution: ``` from sys import stdin, stdout import heapq from collections import defaultdict import math import bisect import io, os # for interactive problem # n = int(stdin.readline()) # print(x, flush=True) #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def main(): MOD = 998244353 #n = int(input()) n,m = list(map(int, stdin.readline().split())) dp_div = [0] * (n+2) dp_div[n+1] = 1 for x in range(n,1,-1): dp_div[x] = (dp_div[x+1] * x) % MOD arr = [] for _ in range(n): arr.append(list(map(int, stdin.readline().split()))) ans = 0 for i in range(m): v = [0] * (n + 2) for j in range(n): x = arr[j][i] v[x] += 1 pos = 0 cnt = 0 for j in range(1,n+1): if pos == -1: break while v[j] > 0: v[j] -= 1 if j == 1: pos = -1 break if cnt == 0: pos = n - j + 1 cnt += 1 continue xx = n - j + 1 yy = n - cnt if xx >= yy: pos = -1 break pos = ((pos * yy) + (xx * dp_div[yy+1]) - (pos * xx)) % MOD cnt+=1 if pos == -1: ans = (ans + dp_div[2]) % MOD else: while cnt != n: pos = (pos * (n - cnt)) % MOD cnt += 1 ans = (ans + pos) % MOD y_inv = 1 for z in range(2, n+1): zz = pow(z, MOD-2, MOD) y_inv = (y_inv * zz) % MOD #print(y_inv) print((ans * y_inv) % MOD) main() ``` Yes
104,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Submitted Solution: ``` # O(n^2*m + mlog(mod)) import sys input = sys.stdin.buffer.readline mod = 998244353 ans = 0 n,m = map(int,input().split()) fact = 1 for i in range(2,n+1): fact = fact * i % mod inv_fact = pow(fact,mod-2,mod) dist = [list(map(int,input().split())) for i in range(n)] # find expected value of each point (LOE) for point in range(m): # if built at or after this time the point will not be conquered by that city time = [n+1 - dist[city][point] + 1 for city in range(n)] add = [0] * (n + 2) for i in time: add[i] += 1 # of ways to place monuments so that they will not conquer the city dp = [[0]*(n+1) for i in range(n+2)] # dp[time][to place (at curr time)] dp[0][0] = 1 for t in range(n+1): for to_place in range(n+1): if dp[t][to_place]: # don't place monument dp[t+1][to_place+add[t+1]] = (dp[t+1][to_place+add[t+1]] + dp[t][to_place]) % mod # place monument if to_place: dp[t+1][to_place-1+add[t+1]] = (dp[t+1][to_place-1+add[t+1]] + to_place*dp[t][to_place]) % mod ans = (ans + (fact - dp[n+1][0])*inv_fact) % mod print(ans) ``` Yes
104,694
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Submitted Solution: ``` mod = 998244353 eps = 10**-9 def main(): import sys from bisect import bisect_left input = sys.stdin.readline N, M = map(int, input().split()) A = [[0] * N for _ in range(M)] for i in range(N): line = list(map(int, input().split())) for j in range(M): A[j][i] = line[j] F = 1 for i in range(1, N+1): F = (F * i)%mod invF = pow(F, mod-2, mod) ans = 0 for B in A: B.sort() tmp = 1 for i in range(N, 0, -1): j = bisect_left(B, i+1) k = max(0, N - j - (N - i)) tmp = (tmp * k)%mod ans = (ans + (F - tmp))%mod print((ans * invF)%mod) if __name__ == '__main__': main() ``` Yes
104,695
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} 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 = 998244353 """ """ primes = [2,3,5,7,11,13,17,19] def solve(): N, M = getInts() dist = [getInts() for _ in range(N)] num = 0 for j in range(M): tmp = [dist[i][j] for i in range(N)] tmp.sort() mult = 1 for i in range(N): mult *= max(tmp[i]-1-i,0) num += mult denom = 1 for i in range(2,N+1): denom *= i num = denom*M - num for i in primes: if i > N: break while num % i == 0 and denom % i == 0: num //= i denom //= i num %= MOD denom %= MOD return (num * (pow(denom,MOD-2,MOD)))%MOD #for _ in range(getInt()): print(solve()) #solve() #TIME_() ``` Yes
104,696
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} Submitted Solution: ``` # region fastio # from https://codeforces.com/contest/1333/submission/75948789 import sys, io, os BUFSIZE = 8192 class FastIO(io.IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = io.BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(io.IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #endregion mod = 998244353 N, M = map(int, input().split()) D = [list(map(int, input().split())) for _ in range(N)] ans = 0 for t in zip(*D): t = sorted(t) p = 1 for i, d in enumerate(t, 1): d -= i p = p * d % mod ans += p denom = 1 for i in range(1, N+1): denom = denom * i % mod print(ans) ans = (M - ans * pow(denom, mod-2, mod)) % mod print(ans) ``` No
104,697
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} 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 = 998244353 LIM = 2*(10**5) # change this bit facs = [1] inv_facs = [1] curr = 1 for j in range(1,LIM+1): curr *= j curr %= MOD facs.append(curr) inv_facs.append(pow(curr,MOD-2,MOD)) def ncr(n,r): return (facs[n]*inv_facs[n-r]*inv_facs[r])%MOD """ """ primes = [2,3,5,7,11,13,17,19] def solve(): N, M = getInts() dist = [getInts() for _ in range(N)] num = 0 for j in range(M): tmp = [dist[i][j] for i in range(N)] tmp.sort() mult = 1 for i in range(N): mult *= max(tmp[i]-1-i,0) num += mult denom = 1 for i in range(2,N+1): denom *= i num = denom - num for i in primes: if i > N: break while num % i == 0: num //= i denom //= i num %= MOD denom %= MOD return (num * (pow(denom,MOD-2,MOD)))%MOD #for _ in range(getInt()): print(solve()) #solve() #TIME_() ``` No
104,698
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn. Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument. Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points! Input The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points. Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point. Output It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1. Example Input 3 5 1 4 4 3 4 1 4 1 4 2 1 4 4 4 3 Output 166374062 Note Let's look at all possible orders of cities Monuments will be build in: * [1, 2, 3]: * the first city controls all points at distance at most 3, in other words, points 1 and 4; * the second city controls all points at distance at most 2, or points 1, 3 and 5; * the third city controls all points at distance at most 1, or point 1. In total, 4 points are controlled. * [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points. * [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points. * [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points. * [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points. The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} 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 = 998244353 """ """ primes = [2,3,5,7,11,13,17,19] def solve(): N, M = getInts() dist = [getInts() for _ in range(N)] num = 0 for j in range(M): tmp = [dist[i][j] for i in range(N)] tmp.sort() mult = 1 for i in range(N): mult *= max(tmp[i]-1-i,0) num += mult denom = 1 for i in range(2,N+1): denom *= i num = denom*M - num for i in primes: if i > N: break while num % i and denom % i == 0: num //= i denom //= i num %= MOD denom %= MOD return (num * (pow(denom,MOD-2,MOD)))%MOD #for _ in range(getInt()): print(solve()) #solve() #TIME_() ``` No
104,699