message
stringlengths
2
433k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
113
108k
cluster
float64
12
12
__index_level_0__
int64
226
217k
Provide tags and a correct Python 3 solution for this coding contest problem. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.
instruction
0
79,205
12
158,410
Tags: implementation Correct Solution: ``` #a def cs(a): for i in range(1,len(a)): if a[i]<a[i-1]: return False return True def recuse(c): if cs(c): return len(c) else: return max(recuse([c[i] for i in range(len(c)//2)]), recuse([c[i] for i in range(len(c)//2,len(c))])) input() print(recuse([int(i) for i in input().split(" ")])) ```
output
1
79,205
12
158,411
Provide tags and a correct Python 3 solution for this coding contest problem. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.
instruction
0
79,206
12
158,412
Tags: implementation Correct Solution: ``` def tanos_sort(a): if a == sorted(a): return len(a) else: return max(tanos_sort(a[len(a) // 2:]), tanos_sort(a[:len(a) // 2])) input() print(tanos_sort(list(map(int, input().split())))) ```
output
1
79,206
12
158,413
Provide tags and a correct Python 3 solution for this coding contest problem. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.
instruction
0
79,207
12
158,414
Tags: implementation Correct Solution: ``` import sys N = int(sys.stdin.readline()) arr = [int(x) for x in sys.stdin.readline().split()] def helper(a, x, y, d): if x > y or y - x == 1: return d m = x + (y - x) // 2 d_l = helper(a, x, m, d + 1) d_r = helper(a, m, y, d + 1) if d_l == d_r == d + 1 and a[m] >= a[m-1]: return d if d_l > d_r: return d_r elif d_r > d_l: return d_l return d_l res = helper(arr, 0, len(arr), 0) if res == 0: print(N) else: print(N // (2*res)) ```
output
1
79,207
12
158,415
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Submitted Solution: ``` mx = 0 def f(a): global mx if a==sorted(a): mx = max(mx, len(a)) else: f(a[:len(a)//2]) f(a[len(a)//2:]) n = int(input()) a = list(map(int, input().split())) f(a) print(mx) ```
instruction
0
79,208
12
158,416
Yes
output
1
79,208
12
158,417
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Submitted Solution: ``` n = int(input()) t = list(map(int,input().split(' '))) def sol(t): s = sorted(t) if all([t[i] == s[i] for i in range(len(t))]): return len(t) return max(sol(t[:int(len(t)/2)]), sol(t[int(len(t)/2):])) print(sol(t)) ```
instruction
0
79,209
12
158,418
Yes
output
1
79,209
12
158,419
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Submitted Solution: ``` def function(a): if sorted(a)==a: return len(a) k=len(a)//2 return max(function(a[:k]),function(a[k:])) n=int(input()) a=[int(x) for x in input().split()] print(function(a)) ```
instruction
0
79,210
12
158,420
Yes
output
1
79,210
12
158,421
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Submitted Solution: ``` n = int(input()) sp = list(map(int, input().split())) max_length = 0 def check_sorted(array): global max_length if array == sorted(array): if len(array) > max_length: max_length = len(array) else: check_sorted(array[:len(array) // 2]) check_sorted(array[len(array) // 2:]) check_sorted(sp) print(max_length) ```
instruction
0
79,211
12
158,422
Yes
output
1
79,211
12
158,423
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) ans = -1 k = n now = 0 while k > 0: for i in range(n // k): now = 1 for j in range(1, k): if a[i * k + j] >= a[i * k + j - 1]: now += 1 else: break ans = max(ans, now) k //= 2 print(ans) ```
instruction
0
79,212
12
158,424
No
output
1
79,212
12
158,425
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Submitted Solution: ``` def sortCheck(lst): if(sorted(lst) != lst): lst.pop(0) return sortCheck(lst) else: lenofarr = len(lst) return lenofarr if __name__ == '__main__': n = int(input()) a = list(map(int,input().strip().split()))[:n] val = sortCheck(a) print(val) ```
instruction
0
79,213
12
158,426
No
output
1
79,213
12
158,427
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Submitted Solution: ``` n = int(input()) a = input().split(' ') for i in range(len(a)): a[i] = int(a[i]) a_sort = a[:] # print(a, a_sort) a_sort.sort() # print(a, a_sort) while a != a_sort: a_length = len(a) del a[0:a_length // 2] a_sort = a[:] a_sort.sort() # print(a, a_sort) print(len(a)) ```
instruction
0
79,214
12
158,428
No
output
1
79,214
12
158,429
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. [Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≤ n ≤ 16) — the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≤ a_i ≤ 100) — the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Submitted Solution: ``` steps = [0,0] def isSorted(array): lastElement = array[0] for i in array: if lastElement <= i: lastElement = i else: return False return True def thanos(array, i): global steps lenght = len(array) if isSorted(array) or lenght == 1: return True else: lenght = lenght // 2 otherArray = array.copy() if i == 0: steps[0]+= 1 steps[1] += 1 else: steps[i-1] += 1 if len(otherArray) > 2: thanos(otherArray[len(otherArray)//2:], 2) thanos(otherArray[:len(otherArray)//2], 1) n = int(input()) numbers = input().split(" ") for i in range(n): numbers[i] = int(numbers[i]) thanos(numbers, 0) print(min(steps)) ```
instruction
0
79,215
12
158,430
No
output
1
79,215
12
158,431
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x. The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub. Input The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a1, a2, ..., an. It is guaranteed that each of those n values is either 0 or 1. Output Print an integer — the maximal number of 1s that can be obtained after exactly one move. Examples Input 5 1 0 0 1 0 Output 4 Input 4 1 0 0 1 Output 4 Note In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1]. In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.
instruction
0
79,435
12
158,870
Tags: brute force, dp, implementation Correct Solution: ``` # Problem Statement: https://codeforces.com/problemset/problem/327/A # solution 1, generate all subarrays and check def solve1(array, n): def count_ones(): ret = 0 for k in range(n): if array[k] == 1: ret += 1 return ret def generate_subarrays(): max_num = 0 for i in range(n): for j in range(i, n): for k in range(i, j+1): array[k] = 1 - array[k] max_num = max(max_num, count_ones()) for k in range(i, j+1): array[k] = 1 - array[k] return max_num return generate_subarrays() # solution 2, using dynamic programming def solve2(array, n): dp = [[0 for x in range(n)] for y in range(n)] max_ones, num1_i_j = 0, 0 for elm in array: num1_i_j += 1 if elm == 1 else 0 for i in range(n): if array[i] == 0: dp[i][i] = num1_i_j + 1 else: dp[i][i] = num1_i_j - 1 max_ones = dp[i][i] if dp[i][i] > max_ones else max_ones for j in range(i+1, n): if j > 0 and array[j] == 0: dp[i][j] = dp[i][j-1] + 1 else: dp[i][j] = dp[i][j-1] - 1 max_ones = dp[i][j] if dp[i][j] > max_ones else max_ones return max_ones # solution 3, using subarray of maximal sum def solve3(array, n): b = [0] * n max_val = [0] * n num_ones = 0 for i in range(n): if array[i] == 1: b[i] = -1 num_ones += 1 else: b[i] = 1 max_val[0] = b[0] for i in range(1, n): if max_val[i-1] + b[i] > b[i]: max_val[i] = max_val[i-1] + b[i] else: max_val[i] = b[i] return num_ones + max(max_val) if __name__ == '__main__': n = int(input()) array = list(map(int, input().split(' '))) print(solve3(array, n)) ```
output
1
79,435
12
158,871
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x. The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub. Input The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a1, a2, ..., an. It is guaranteed that each of those n values is either 0 or 1. Output Print an integer — the maximal number of 1s that can be obtained after exactly one move. Examples Input 5 1 0 0 1 0 Output 4 Input 4 1 0 0 1 Output 4 Note In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1]. In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.
instruction
0
79,436
12
158,872
Tags: brute force, dp, implementation Correct Solution: ``` import heapq as hp import collections import bisect def unpack(func=int): return map(func, input().split()) def l_unpack(func=int): """list unpack""" return list(map(func, input().split())) def s_unpack(func=int): """sorted list unpack""" return sorted(map(func, input().split())) def range_n(): return range(int(input())) def counter(a): d = {} for x in a: if x in d: d[x] += 1 else: d[x] = 1 return d def setbits(x): count = 0 while x: x = x & (x - 1) count += 1 return count def getint(): return int(input()) def kadens(arr): ans = 0 ans = arr[0] for i in range(1, len(arr)): arr[i] = max(arr[i - 1] + arr[i], arr[i]) ans = max(ans, arr[i]) return ans def main(): n = getint() a = [] ss = 0 for i in unpack(): a.append(-1 if i else 1) ss += i ans = ss + kadens(a) print(ans) main() ```
output
1
79,436
12
158,873
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
instruction
0
79,516
12
159,032
Tags: bitmasks, divide and conquer, math Correct Solution: ``` __author__ = 'yushchenko' def countf(f): sum = 0 for i in range(len(f)): for j in range(len(f))[i:]: # print(i, j) # print(f[i:j + 1]) sum += min(f[i:j + 1]) return sum import itertools n,m = input().split() n = int(n) m = int(m) if n == 1: print(1) exit() maxcount = pow(2, n - 2) t = 1 saved = [] result = [] for i in range (n): # print(maxcount, m) while m > maxcount: m -= maxcount if maxcount > 1: maxcount /= 2 saved.append(t) t += 1 else: result.append(str(t)) if maxcount > 1: maxcount /= 2 t += 1 if t > n: break for x in reversed(saved): result.append(str(x)) print(' '.join(result)) ```
output
1
79,516
12
159,033
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
instruction
0
79,517
12
159,034
Tags: bitmasks, divide and conquer, math Correct Solution: ``` (n,m)=input().split() (n,m)=(int(n),int(m)-1) pow2=[] u=1 for i in range(n): pow2.append(u) u*=2 r=[] k=1 while k<n: if m<pow2[n-k-1]: r.append(k) else: m-=pow2[n-k-1] k+=1 z=[] for i in range(n): if not (n-i in r): z.append(n-i) r+=z r=[str(i) for i in r] print(' '.join(r)) ```
output
1
79,517
12
159,035
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
instruction
0
79,518
12
159,036
Tags: bitmasks, divide and conquer, math Correct Solution: ``` ip=[int(i) for i in input().split()] n,m=ip[0],(ip[1]-1) per='0'*(n+1-len(bin(m)))+bin(m)[2:len(bin(m))] p=str(n) for i in range (n-1,0,-1): if per[i-1]=='0': p=str(i)+' '+p else: p=p+' '+str(i) print(p) ```
output
1
79,518
12
159,037
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
instruction
0
79,519
12
159,038
Tags: bitmasks, divide and conquer, math Correct Solution: ``` n, m = map(int, input().split()); res = [] num = 0 x = n for i in range(1, n): if i not in res: if pow(2, x - len(res) - 2) + num >= m: res.append(i); else: num += pow(2, x - len(res) - 2); x -= 1; i = n; while i > 0: if i not in res: res.append(i); i -= 1; for i in res: print(i, end = " "); print(); ```
output
1
79,519
12
159,039
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
instruction
0
79,520
12
159,040
Tags: bitmasks, divide and conquer, math Correct Solution: ``` n, m = map(int, input().split()) s = 0 flag = False k = 0 myset = set() flag1 = True for j in range(n): if n in myset: for i in range(n, 0, -1): if i not in myset: print(i, end = ' ') flag1 = False if flag1 == False: break flag = False s = 0 for i in range(n): if s < m <= s + 2**(n - i - 2 - k): print(i + 1 + k, end = ' ') myset.add(i + 1 + k) k = i + 1 + k flag = True break s += (2**(n - i - 2 - k)) if flag == False: print(n, end = ' ') myset.add(n) k = n m -= s ```
output
1
79,520
12
159,041
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
instruction
0
79,521
12
159,042
Tags: bitmasks, divide and conquer, math Correct Solution: ``` arc = [] def sv(a,b,c,n,v): if n < c//2: arc[a] = v if b-a>1: sv(a+1,b,c//2,n,v+1) else: arc[b-1] = v if b-a>1: sv(a,b-1,c//2,n-c//2,v+1) n, m = map(int, input().split()) arc = [0]*n ssc = 1<<(n-1) sv(0, n, ssc, m-1, 1) print(' '.join(map(str, arc))) ```
output
1
79,521
12
159,043
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
instruction
0
79,522
12
159,044
Tags: bitmasks, divide and conquer, math Correct Solution: ``` n, m = map(int, input().split()) seq = [i for i in range(1, n+1)] m -= 1 dig = [] digs = 0 while m > 0: dig.append(m % 2) m //= 2 digs += 1 swap = 0 sw = [0] * digs for i in range(digs - 1, -1, -1): if swap == 1: sw[i] = 1 - dig[i] else: sw[i] = dig[i] swap = (swap + sw[i]) % 2 for i in range(digs): if sw[i] == 1: seq[-i-2:] = seq[:-i-3:-1] print(" ".join(map(str, seq))) ```
output
1
79,522
12
159,045
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
instruction
0
79,523
12
159,046
Tags: bitmasks, divide and conquer, math Correct Solution: ``` ii=lambda:int(input()) kk=lambda:map(int, input().split()) ll=lambda:list(kk()) n,k=kk() pre,post = [],[] k-=1 v = 1 for i in range(n-2,-1,-1): if k&(2**i): post.append(v) else: pre.append(v) v+=1 print(*pre,n,*reversed(post)) ```
output
1
79,523
12
159,047
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. Submitted Solution: ``` n, m = map(int, input().split()) lst = [0] * n l, r = 0, n - 1 i = 1 while (r > l): if m > 2 ** (r - l - 1): lst[r] = i m -= 2 ** (r - l - 1) r -= 1 else: lst[l] = i l += 1 i += 1 lst[l] = i print(' '.join(map(str, lst))) ```
instruction
0
79,524
12
159,048
Yes
output
1
79,524
12
159,049
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. Submitted Solution: ``` """ Codeforces Rockethon Contest Problem B Author : chaotic_iak Language: Python 3.4.2 """ ################################################### SOLUTION def main(): n,m = read() m -= 1 perm = [0]*n lf = 0 rt = n-1 for i in range(n): if m >= 2**(n-i-2): perm[rt] = i+1 rt -= 1 else: perm[lf] = i+1 lf += 1 m %= 2**(n-i-2) write(perm) #################################################### HELPERS def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: return list(map(int, inputs.split())) def write(s="\n"): if s is None: s = "" if isinstance(s, list): s = " ".join(map(str, s)) s = str(s) print(s, end="") write(main()) ```
instruction
0
79,525
12
159,050
Yes
output
1
79,525
12
159,051
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. Submitted Solution: ``` def main(): n, m = map(int, input().split()) m -= 1 aa = [0] * n lo, hi = 0, n - 1 t = 2 ** (n - 2) for i in range(1, n + 1): if m < t: aa[lo] = i lo += 1 else: aa[hi] = i hi -= 1 m -= t t //= 2 print(*aa) if __name__ == '__main__': main() ```
instruction
0
79,526
12
159,052
Yes
output
1
79,526
12
159,053
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. Submitted Solution: ``` import sys def read_input(input_path=None): if input_path is None: f = sys.stdin else: f = open(input_path, 'r') n, m = map(int, f.readline().split()) return n, m def sol(n, m): v = [0 for _ in range(n+1)] left, right = 1, n for i in range(1, n + 1): if n - i - 1 <= 0: pw = 1 else: pw = 1 << (n - i - 1) if m <= pw: v[left] = i left += 1 else: v[right] = i right -= 1 m -= pw return [' '.join(map(str, v[1:]))] def solve(input_path=None): return sol(*read_input(input_path)) def main(): for line in sol(*read_input()): print(f"{line}") if __name__ == '__main__': main() ```
instruction
0
79,527
12
159,054
Yes
output
1
79,527
12
159,055
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. Submitted Solution: ``` import math def solve(N, M, offset): if N <= 0: return "" z = math.factorial(N - 1) i = 0 s = 0 while M >= s: s += z i += 1 i-=1 s-=z return " " + str(offset[i]) + solve(N - 1, M - s, offset[:(i)] + offset[i+1:]) if __name__ == '__main__': s = input() ns, ms, = s.split() N = int(ns) M = int(ms) l = [x for x in range(1, N + 1)] print(solve(N, M - 1, l)[1:]) ```
instruction
0
79,528
12
159,056
No
output
1
79,528
12
159,057
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. Submitted Solution: ``` ip=[int(i) for i in input().split()] n,m=ip[0],(ip[1]-1) per='0'*(n+1-len(bin(m)))+bin(m)[2:len(bin(m))] p=str(n) for i in range (n-1,0,-1): if per[i-1]=='0': p=str(i)+' '+p else: p=p+' '+str(i) print(' '.join(list(p))) ```
instruction
0
79,529
12
159,058
No
output
1
79,529
12
159,059
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. Submitted Solution: ``` n, m = map(int, input().split()) t = [] while n: if m > 1 << n: m -= 1 << n t += [n] else: t = [n] + t n -= 1 for q in t: print(q) ```
instruction
0
79,530
12
159,060
No
output
1
79,530
12
159,061
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. Submitted Solution: ``` def gen_all(i, j, p, n, a): if p > n: yield a return a[i] = p yield from gen_all(i + 1, j, p + 1, n, a) a[j - 1] = p yield from gen_all(i, j - 1, p + 1, n, a) n, m = map(int, input().split()) it = gen_all(0, n, 1, n, [0] * n) for _ in range(m): ans = next(it) # print(ans) print(' '.join(map(str, ans))) ```
instruction
0
79,531
12
159,062
No
output
1
79,531
12
159,063
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem. You are given integer k and array a1, a2, ..., an of n integers. You are to find non-empty subsequence of array elements such that the product of its elements is divisible by k and it contains minimum possible number of elements. Formally, you are to find a sequence of indices 1 ≤ i1 < i2 < ... < im ≤ n such that <image> is divisible by k while m is minimum possible among all such variants. If there are more than one such subsequences, you should choose one among them, such that sum of its elements is minimum possible. Mishka quickly solved this problem. Will you do so? Input The first line of the input contains two integers n and k (1 ≤ n ≤ 1 000, 1 ≤ k ≤ 1012). The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1012) — array elements. Output Print single positive integer m in the first line — the number of elements in desired sequence. In the second line print m distinct integers — the sequence of indices of given array elements, which should be taken into the desired sequence. If there are more than one such subsequence (e.g. subsequence of minimum possible number of elements and with minimum possible sum of elements), you can print any of them. If there are no such subsequences, print - 1 in the only line. Example Input 5 60 2 4 6 5 2 Output 3 4 3 1 Submitted Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- r""" Excited Nasy! O._.O (\=/) @author: Nasy @email: sy_n@me.com @date: Apr 19, 2017 @licens: MIT Q """ import sys def cb(iterable, r): """Combinations.""" pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) def main(): """Main function.""" n, k = (int(i) for i in sys.stdin.readline().replace("\n", "").split(" ")) arr = {i+1:int(e) for i,e in enumerate(sys.stdin.readline().replace("\n", "").split(" "))} ary = sorted(arr.items(), key=lambda x: x[1]) for c in range(2, n+1): for i in cb(ary, c): a = 1 for j in i: a *= j[1] if a // 60: print(*(k[0] for k in i)) return print(-1) return if __name__ == "__main__": main() ```
instruction
0
79,601
12
159,202
No
output
1
79,601
12
159,203
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem. You are given integer k and array a1, a2, ..., an of n integers. You are to find non-empty subsequence of array elements such that the product of its elements is divisible by k and it contains minimum possible number of elements. Formally, you are to find a sequence of indices 1 ≤ i1 < i2 < ... < im ≤ n such that <image> is divisible by k while m is minimum possible among all such variants. If there are more than one such subsequences, you should choose one among them, such that sum of its elements is minimum possible. Mishka quickly solved this problem. Will you do so? Input The first line of the input contains two integers n and k (1 ≤ n ≤ 1 000, 1 ≤ k ≤ 1012). The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1012) — array elements. Output Print single positive integer m in the first line — the number of elements in desired sequence. In the second line print m distinct integers — the sequence of indices of given array elements, which should be taken into the desired sequence. If there are more than one such subsequence (e.g. subsequence of minimum possible number of elements and with minimum possible sum of elements), you can print any of them. If there are no such subsequences, print - 1 in the only line. Example Input 5 60 2 4 6 5 2 Output 3 4 3 1 Submitted Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- r""" Excited Nasy! O._.O (\=/) @author: Nasy @email: sy_n@me.com @date: Apr 22, 2017 @licens: MIT Q """ import sys def cb(iterable, r): """Combinations.""" pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) def main(): """Main function.""" n, k = (int(i) for i in sys.stdin.readline().replace("\n", "").split(" ")) arr = {i+1:int(e) for i,e in enumerate(sys.stdin.readline().replace("\n", "").split(" "))} ary = sorted(arr.items(), key=lambda x: x[1]) for c in range(2, n+1): for i in cb(ary, c): a = 1 for j in i: a *= j[1] if a // 60: print(*(k[0] for k in i)) return print(-1) return if __name__ == "__main__": main() ```
instruction
0
79,602
12
159,204
No
output
1
79,602
12
159,205
Provide tags and a correct Python 3 solution for this coding contest problem. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1].
instruction
0
80,039
12
160,078
Tags: string suffix structures Correct Solution: ``` n = int(input()) m = 998244353 p,p_,mul = 1,0,n def getp(): global p,p_,mul p_ = p p = (p*mul)%m mul -= 1 return (p-p_+m)%m ans = 1+sum([i*getp() for i in range(1,n)]) print(ans%m) ```
output
1
80,039
12
160,079
Provide tags and a correct Python 3 solution for this coding contest problem. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1].
instruction
0
80,040
12
160,080
Tags: string suffix structures Correct Solution: ``` import math def solution(n): m_var = 998244353 p_var = n a_var= 0 for i in range(n, 1, -1): a_var = (a_var+ p_var * (i - 1) * (n - i + 1) - p_var) % m_var p_var = p_var * i % m_var a_var = (p_var * (p_var - n + 2) - 2 * a_var) % m_var if a_var & 1: a_var += m_var return a_var // 2 x = int(input()) ans = solution(x) print(ans) ```
output
1
80,040
12
160,081
Provide tags and a correct Python 3 solution for this coding contest problem. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1].
instruction
0
80,041
12
160,082
Tags: string suffix structures Correct Solution: ``` n = int(input()) if (n == 1): print(1) exit(0) if (n == 2): print(2) exit(0) a = [] n+=1 a.append(9) iter = 1 nn=4 m = 6 for i in range(nn , n): m *= i m %= 998244353 a.append((a[iter-1]-1)*nn+m) a[iter] %= 998244353 nn+=1 iter += 1 print(a[iter-1]) ```
output
1
80,041
12
160,083
Provide tags and a correct Python 3 solution for this coding contest problem. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1].
instruction
0
80,042
12
160,084
Tags: string suffix structures Correct Solution: ``` def factorial_mod(n, mod): ans = 1 for i in range(1, n + 1): ans = (ans * i) % mod return ans def solve(n): if n == 1: return 1 elif n == 2: return 2 mod = 998244353 len_metaseq = factorial_mod(n, mod) ans = ( ((n - 1) + (n - 2)) * len_metaseq * 499122177 # modinv(2, mod) ) % mod error = 0 for curr in range(4, n + 1): error = ((error + 1) * curr) % mod return (ans - error) % mod n = int(input()) print(solve(n)) ```
output
1
80,042
12
160,085
Provide tags and a correct Python 3 solution for this coding contest problem. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1].
instruction
0
80,043
12
160,086
Tags: string suffix structures Correct Solution: ``` md = 998244353 n = int(input()) p = 1 ans = 0 for i in range(n - 1): p = (p * (n - i)) % md ans -= p ans += n * p print(ans % md) ```
output
1
80,043
12
160,087
Provide tags and a correct Python 3 solution for this coding contest problem. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1].
instruction
0
80,044
12
160,088
Tags: string suffix structures Correct Solution: ``` n = int(input()) M = 998244353 f = n s = n for i in range(1, n): f = f * (n - i) x = n - i - 1 y = (f * x) // (x + 1) s += (i + 1) * y s %= M f %= M print(s % M) ```
output
1
80,044
12
160,089
Provide tags and a correct Python 3 solution for this coding contest problem. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1].
instruction
0
80,045
12
160,090
Tags: string suffix structures Correct Solution: ``` n = int(input()) def fun(n): if n==1: return 1 else: cur = n for i in range(1, n): cur = (cur - 1) * (i+1) % 998244353 return(cur) print(fun(n)) # t = int(input()) # res = t # i = 2 # while(i<=t): # res = (res-1)*i%998244353 # i+=1 # print(res) ```
output
1
80,045
12
160,091
Provide tags and a correct Python 3 solution for this coding contest problem. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1].
instruction
0
80,046
12
160,092
Tags: string suffix structures Correct Solution: ``` def solve(): n = int(input()) factorials = [0,1,2,6,24,120] subtract = [0,0,2,9,40,205] for item in range(6,n+1): factorials.append((factorials[-1]*item)%998244353) subtract.append(((subtract[-1]+1)*item)%998244353) print (((n*factorials[n])%998244353-subtract[n])%998244353) solve() ```
output
1
80,046
12
160,093
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. Submitted Solution: ``` n, ans, mod, r = int(input()), 1, 998244353, 0 for i in range(2, n + 1): ans = ans * i % mod r = (r + 1) * i % mod print((((ans * n - r) % mod) + mod) % mod) ```
instruction
0
80,047
12
160,094
Yes
output
1
80,047
12
160,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. Submitted Solution: ``` import math n = int(input()) mod = 998244353 F = [1, 1] f = 1 for i in range(2,n+1): f*=i f%=mod F.append(f) ret = 1 for i in range(1, n+1): ret=ret*i-i+F[i] ret%=mod print(ret) ```
instruction
0
80,048
12
160,096
Yes
output
1
80,048
12
160,097
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction from collections import defaultdict 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----------------------------------------------------- dp = [None] * 1000006 mod = 998244353 n = int(input()) dp[1] = n for i in range(2, n + 1): dp[i] = (n - i + 1) * dp[i - 1] % mod ans = dp[n] * n % mod for i in range(1, n): ans = (ans + mod - dp[i]) % mod print(ans) ```
instruction
0
80,049
12
160,098
Yes
output
1
80,049
12
160,099
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. Submitted Solution: ``` mod=998244353 n=int(input()) ans=n for i in range(2,n+1): ans=((ans-1)*i)%mod print(ans) ```
instruction
0
80,050
12
160,100
Yes
output
1
80,050
12
160,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. Submitted Solution: ``` import math def solution(n): var1 = 998244353 var3 = n var2 = 0 i=n while(i>=0): var2 = (var2 + var3 * (i - 1) * (n - i + 1) - var3) % var1 var3 = var3 * i % var1 i-=1 var2 = (var3 * (var3 - n + 2) - 2 * var2) % var1 if var2 & 1: var2 += var1 return var2 // 2 x = int(input()) ans = solution(x) print(ans) ```
instruction
0
80,051
12
160,102
No
output
1
80,051
12
160,103
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. Submitted Solution: ``` n=int(input()) if n==1: print(1) exit(0) if n==2: print(2) exit(0) ans=1 for i in range(1,n+1): ans=ans*i%998244353 ans2=ans ans=int(ans/2)*(2*n-3)%998244353 ans2=ans2/6 for i in range(3,n): ans=int(ans-ans2%998244353)%998244353 ans2=(ans2/(i+1))%998244353 print(int(ans%998244353)) ```
instruction
0
80,052
12
160,104
No
output
1
80,052
12
160,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. Submitted Solution: ``` def perm(n,i): t = 1 for i in range(n+1-i,n+1): t = t * i return t n = int(input()) sum = 0 sum = sum + perm(n,n) for i in range(2,n): sum = sum + perm(n,n-i)*(perm(i,i)-1) print(int(sum)) ```
instruction
0
80,053
12
160,106
No
output
1
80,053
12
160,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (P_i, P_{i+1}, ..., P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). Input The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement. Output Output a single integer — the number of distinct subarrays, modulo 998244353. Examples Input 2 Output 8 Input 10 Output 19210869 Note In the first example, the sequence P = [1, 2, 2, 1]. It has eight distinct subarrays: [1], [2], [1, 2], [2, 1], [2, 2], [1, 2, 2], [2, 2, 1] and [1, 2, 2, 1]. Submitted Solution: ``` n = int(input()) dd = 998244353 dp = [(1,0), (1, 0), (2, 0), (6, 3)] if n == 1: print(1) elif n == 2: print(2) for i in range(4, n+1): np = (dp[-1][0]*i, i*(dp[-1][0]-1) + i*(dp[-1][1])) np = (np[0] % dd, np[1] % dd) dp.append(np) print((dp[-1][0] + dp[-1][1]) % dd) ```
instruction
0
80,054
12
160,108
No
output
1
80,054
12
160,109
Provide tags and a correct Python 3 solution for this coding contest problem. This is the easy version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 2000). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2000). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3.
instruction
0
80,103
12
160,206
Tags: binary search, brute force, combinatorics, math, number theory, sortings Correct Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * 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().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) #------------------------------------------------------------------------ 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 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 ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa=ifa[::-1] 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 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 def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m 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,arr): self.n=len(arr)-1 self.arr=[0]*(self.n<<2) self.lazy=[0]*(self.n<<2) def Build(l,r,rt): if l==r: self.arr[rt]=arr[l] return m=(l+r)>>1 Build(l,m,rt<<1) Build(m+1,r,rt<<1|1) self.pushup(rt) Build(1,self.n,1) def pushup(self,rt): self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1] def pushdown(self,rt,ln,rn):#lr,rn表区间数字数 if self.lazy[rt]: self.lazy[rt<<1]+=self.lazy[rt] self.lazy[rt<<1|1]=self.lazy[rt] self.arr[rt<<1]+=self.lazy[rt]*ln self.arr[rt<<1|1]+=self.lazy[rt]*rn self.lazy[rt]=0 def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间 if r==None: r=self.n if L<=l and r<=R: self.arr[rt]+=c*(r-l+1) self.lazy[rt]+=c return m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) if L<=m: self.update(L,R,c,l,m,rt<<1) if R>m: self.update(L,R,c,m+1,r,rt<<1|1) self.pushup(rt) def query(self,L,R,l=1,r=None,rt=1): if r==None: r=self.n #print(L,R,l,r,rt) if L<=l and R>=r: return self.arr[rt] m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) ans=0 if L<=m: ans+=self.query(L,R,l,m,rt<<1) if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1) return ans ''' 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 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 def GP(it): return [(ch,len(list(g))) for ch,g in groupby(it)] class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None t=1 for i in range(t): n,p=RL() a=RLL() a.sort() mi=max(a[i]-i for i in range(n)) ma=a[-1]-1 if mi>ma: print(0) print() exit() j=cur=0 res=[] for i in range(mi,ma+n): while j<n and a[j]<=i: j+=1 cur+=1 res.append((i-cur)%p) c=Counter() ans=[] for r in range(n): c[res[r]]+=1 if c[mi%p]==0: ans.append(mi) r=n for x in range(mi+1,ma+1): c[res[r]]+=1 c[res[r-n]]-=1 if c[x%p]==0: ans.append(x) r+=1 print(len(ans)) print(*ans) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ```
output
1
80,103
12
160,207
Provide tags and a correct Python 3 solution for this coding contest problem. This is the easy version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 2000). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2000). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3.
instruction
0
80,104
12
160,208
Tags: binary search, brute force, combinatorics, math, number theory, sortings Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- 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") # -------------------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 avl=AvlTree() #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', 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 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------------------------------------ n,p=map(int,input().split()) l=list(map(int,input().split())) l.sort() tot=[] ind=defaultdict(int) for i in range(len(l)): ind[l[i]]=i+1 for i in range(1,5001): if ind[i]==0: ind[i]=ind[i-1] for i in range(1,max(l)+1): ans=1 y=0 for j in range(n): ans=(ind[j+i]-j) if ans<0: y=1 break if ans%p==0: y=1 break if y==0: tot.append(i) print(len(tot)) print(*tot,sep=' ') ```
output
1
80,104
12
160,209
Provide tags and a correct Python 3 solution for this coding contest problem. This is the easy version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 2000). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2000). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3.
instruction
0
80,105
12
160,210
Tags: binary search, brute force, combinatorics, math, number theory, sortings Correct Solution: ``` def asterism(p, a): n, m, M = len(a), 1, max(a) - 1 for i in range(n): m = max(m, a[i] - i) for i in range(n - p + 1): M = min(M, a[p + i - 1] - i - 1) print(max(0, M - m + 1)) for i in range(m, M+1): print(i, end=' ') asterism(int(input().split()[1]), sorted([int(i) for i in input().split()])) ```
output
1
80,105
12
160,211