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. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
instruction
0
106,529
12
213,058
Tags: dp, implementation, two pointers Correct Solution: ``` length = int(input()) nums = [int(num) for num in input().split()] + [float('inf'), float('-inf')] ans, small, big = 0, 0, 0 for i in range(length): if nums[i] > nums[i - 1]: small += 1 big += 1 else: ans = max(ans, small + 1, big) big = small + 1 if nums[i + 1] > nums[i - 1] + 1 or nums[i] > nums[i - 2] + 1 else 2 if nums[i + 1] > nums[i]: small = 1 else: small = 0 print(max(ans, big)) ```
output
1
106,529
12
213,059
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
instruction
0
106,530
12
213,060
Tags: dp, implementation, two pointers Correct Solution: ``` n = int(input()) A = [int(ele) for ele in input().split(" ")] if n <= 2: print(n) else: LISend = [1] * n LISbegin = [1] * n for i in range(1,n): if A[i] > A[i-1]: LISend[i] = LISend[i-1] + 1 for i in range(n-2,-1,-1): if A[i] < A[i+1]: LISbegin[i] = LISbegin[i+1] + 1 maxLength = 0 for i in range(1,n-1): if A[i+1] - A[i-1] >= 2: maxLength = max(LISend[i-1] + 1 + LISbegin[i+1], maxLength) maxLength = max(LISbegin[1] + 1, maxLength) maxLength = max(LISend[n-2] + 1, maxLength) maxLength = max(min(n, max(LISbegin) + 1), maxLength) print(maxLength) ```
output
1
106,530
12
213,061
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
instruction
0
106,531
12
213,062
Tags: dp, implementation, two pointers Correct Solution: ``` def main(): n = int(input()) a = [10 ** 10] + list(map(int, input().split())) + [-(10 ** 10)] if n == 1: print(1) exit() b = [0] * (n + 10) c = [0] * (n + 10) #print(a, b, c) i = 1 while i <= n: for j in range(i, n+1): if a[j] >= a[j+1]: break for k in range(i, j+1): b[k] = i c[k] = j i = j + 1 #print(c,b) ans = max(c[2], n - b[n-1] + 1, c[1], n - b[n] + 1) for i in range(2, n): ans = max(ans, c[i] - i + 2, i - b[i] + 2) if a[i - 1]+ 1 < a[i+1]: ans = max(ans, c[i+1] - b[i-1] + 1) print(ans) if __name__ == '__main__': main() ```
output
1
106,531
12
213,063
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: 1. Pick a random segment (continuous subsequence) from l to r. All <image> segments are equiprobable. 2. Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1, p2, ..., pk. All k! permutation are equiprobable. 3. This permutation is applied to elements of the chosen segment, i.e. permutation a1, a2, ..., al - 1, al, al + 1, ..., ar - 1, ar, ar + 1, ..., an is transformed to a1, a2, ..., al - 1, al - 1 + p1, al - 1 + p2, ..., al - 1 + pk - 1, al - 1 + pk, ar + 1, ..., an. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and ai > aj. Find the expected number of inversions after we apply exactly one operation mentioned above. Input The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the length of the permutation. The second line contains n distinct integers from 1 to n β€” elements of the permutation. Output Print one real value β€” the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 9. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Example Input 3 2 3 1 Output 1.916666666666666666666666666667
instruction
0
106,674
12
213,348
Tags: data structures, probabilities Correct Solution: ``` # Python3 program to count inversions using # Binary Indexed Tree # Returns sum of arr[0..index]. This function # assumes that the array is preprocessed and # partial sums of array elements are stored # in BITree[]. def getSum( BITree, index): sum = 0 # Initialize result # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates a node in Binary Index Tree (BITree) # at given index in BITree. The given value # 'val' is added to BITree[i] and all of its # ancestors in tree. def updateBIT(BITree, n, index, val): # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent # in update View index += index & (-index) # Returns count of inversions of size three def getInvCount(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(1, maxElement + 1): BIT[i] = 0 for i in range(n - 1, -1, -1): invcount += getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], 1) return invcount def getInvCountAdv(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(1, maxElement + 1): BIT[i] = 0 for i in range(n - 1, -1, -1): invcount += (i + 1) * getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], n-i) return invcount # Driver code n = int(input()) a = list(map(int,input().split())) InvCount = getInvCount(a, n) InvCountAdv = getInvCountAdv(a,n) thirdSum = 0 for i in range(1,n+1): thirdSum += i * (i - 1) * (n- i + 1) / 2 print(InvCount - InvCountAdv / (n * (n + 1)) * 2 + thirdSum / (n * (n + 1))) # Some part of this code is contributed by # Shubham Singh(SHUBHAMSINGH10) ```
output
1
106,674
12
213,349
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: 1. Pick a random segment (continuous subsequence) from l to r. All <image> segments are equiprobable. 2. Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1, p2, ..., pk. All k! permutation are equiprobable. 3. This permutation is applied to elements of the chosen segment, i.e. permutation a1, a2, ..., al - 1, al, al + 1, ..., ar - 1, ar, ar + 1, ..., an is transformed to a1, a2, ..., al - 1, al - 1 + p1, al - 1 + p2, ..., al - 1 + pk - 1, al - 1 + pk, ar + 1, ..., an. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and ai > aj. Find the expected number of inversions after we apply exactly one operation mentioned above. Input The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the length of the permutation. The second line contains n distinct integers from 1 to n β€” elements of the permutation. Output Print one real value β€” the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 9. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Example Input 3 2 3 1 Output 1.916666666666666666666666666667
instruction
0
106,675
12
213,350
Tags: data structures, probabilities Correct Solution: ``` # Python3 program to count inversions using # Binary Indexed Tree # Returns sum of arr[0..index]. This function # assumes that the array is preprocessed and # partial sums of array elements are stored # in BITree[]. def getSum( BITree, index): sum = 0 # Initialize result # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates a node in Binary Index Tree (BITree) # at given index in BITree. The given value # 'val' is added to BITree[i] and all of its # ancestors in tree. def updateBIT(BITree, n, index, val): # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent # in update View index += index & (-index) # Returns count of inversions of size three def getInvCount(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(1, maxElement + 1): BIT[i] = 0 for i in range(n - 1, -1, -1): invcount += getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], 1) return invcount def getInvCountAdv(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(1, maxElement + 1): BIT[i] = 0 for i in range(n - 1, -1, -1): invcount += (i + 1) * getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], n-i) return invcount # Driver code n = int(input()) a = list(map(int,input().split())) InvCount = getInvCount(a, n) InvCountAdv = getInvCountAdv(a,n) thirdSum = 0 for i in range(1,n+1): thirdSum += i * (i - 1) * (n- i + 1) / 2 print(InvCount - InvCountAdv / (n * (n + 1)) * 2 + thirdSum / (n * (n + 1))) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10) ```
output
1
106,675
12
213,351
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 of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: 1. Pick a random segment (continuous subsequence) from l to r. All <image> segments are equiprobable. 2. Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1, p2, ..., pk. All k! permutation are equiprobable. 3. This permutation is applied to elements of the chosen segment, i.e. permutation a1, a2, ..., al - 1, al, al + 1, ..., ar - 1, ar, ar + 1, ..., an is transformed to a1, a2, ..., al - 1, al - 1 + p1, al - 1 + p2, ..., al - 1 + pk - 1, al - 1 + pk, ar + 1, ..., an. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and ai > aj. Find the expected number of inversions after we apply exactly one operation mentioned above. Input The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the length of the permutation. The second line contains n distinct integers from 1 to n β€” elements of the permutation. Output Print one real value β€” the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 9. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Example Input 3 2 3 1 Output 1.916666666666666666666666666667 Submitted Solution: ``` # Python3 program to count inversions using # Binary Indexed Tree # Returns sum of arr[0..index]. This function # assumes that the array is preprocessed and # partial sums of array elements are stored # in BITree[]. def getSum( BITree, index): sum = 0 # Initialize result # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates a node in Binary Index Tree (BITree) # at given index in BITree. The given value # 'val' is added to BITree[i] and all of its # ancestors in tree. def updateBIT(BITree, n, index, val): # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent # in update View index += index & (-index) # Returns count of inversions of size three def getInvCount(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(1, maxElement + 1): BIT[i] = 0 for i in range(n - 1, -1, -1): invcount += getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], 1) return invcount def getInvCountAdv(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(1, maxElement + 1): BIT[i] = 0 for i in range(n - 1, -1, -1): invcount += (i + 1) * getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], n-i) return invcount n = int(input()) a = list(map(int,input().split())) InvCount = getInvCount(a, n) InvCountAdv = getInvCountAdv(a,n) print(InvCountAdv) thirdSum = 0 for i in range(1,n+1): thirdSum += i * (i - 1) * (n- i + 1) / 2 print(thirdSum) print(InvCount - InvCountAdv / (n * (n + 1)) * 2 + thirdSum / (n * (n + 1))) # This code uses "Counting Inversion" contributed by SHUBHAMSINGH10 ```
instruction
0
106,676
12
213,352
No
output
1
106,676
12
213,353
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
instruction
0
106,688
12
213,376
Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` from collections import defaultdict def DFS(d,visited,x): stack = [x] ans = [] while len(stack): temp = stack.pop() visited[temp] = 1 ans.append(temp+1) for i in d[temp]: if visited[i] == 0: stack.append(i) visited[temp] = 1 return ans n = int(input()) l = list(map(int,input().split())) act_pos = {l[i]:i for i in range(n)} pos = [] t = sorted(l) pos = {t[i]:i for i in range(n)} d = defaultdict(list) for i in l: d[act_pos[i]].append(pos[i]) visited = [0 for i in range(n)] ans = [] for i in range(n): if visited[i] == 0: k = list(DFS(d,visited,i)) t1 = k[::-1] t1.append(len(k)) ans.append(t1[::-1]) print(len(ans)) for i in ans: print(*i) ```
output
1
106,688
12
213,377
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
instruction
0
106,689
12
213,378
Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) a = sorted(zip(map(int, input().split()), range(n))) s = [] for i in range(n): if a[i]: s.append([]) while a[i]: s[-1].append(i + 1) a[i], i = None, a[i][1] print(len(s)) for l in s: print(len(l), *l) ```
output
1
106,689
12
213,379
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
instruction
0
106,690
12
213,380
Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` # -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random import itertools """ created by shhuan at 2017/10/20 10:12 """ N = int(input()) A = [int(x) for x in input().split()] B = [x for x in A] B.sort() ind = {v: i for i,v in enumerate(B)} order = [ind[A[i]] for i in range(N)] done = [0] * N ans = [] for i in range(N): if not done[i]: g = [] cur = i while not done[cur]: g.append(cur) done[cur] = 1 cur = order[cur] ans.append([len(g)] + [j+1 for j in g]) print(len(ans)) for row in ans: print(' '.join(map(str, row))) ```
output
1
106,690
12
213,381
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
instruction
0
106,691
12
213,382
Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` from sys import stdin n = int(stdin.readline().strip()) a = list(map(int, stdin.readline().strip().split())) a = [(a[i], i+1) for i in range(n)] a.sort() used = [False]*(n+1) ss = [] for i in range(1, n+1): if not used[i]: s = [i] used[i] = True j = i while True: j = a[j-1][1] if not used[j]: s.append(j) used[j] = True else: break ss.append(s) print(len(ss)) for s in ss: print(len(s), ' '.join(list(map(str, s)))) ```
output
1
106,691
12
213,383
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
instruction
0
106,692
12
213,384
Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` import sys n = int(input()) a = list(map(int, input().split())) a = sorted([(a[i], i) for i in range(n)]) d = [] c = [False]*n for i in range(n): if not c[i]: k = i p = [] while not c[k]: c[k] = True p.append(str(k+1)) k = a[k][1] d.append(p) print(len(d)) for i in d: print(str(len(i))+" "+" ".join(i)) ```
output
1
106,692
12
213,385
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
instruction
0
106,693
12
213,386
Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` import operator as op input() a = list(x[0] for x in sorted(enumerate(map(int, input().split())), key=op.itemgetter(1))) ans = [] for i in range(len(a)): if a[i] != -1: j = a[i] a[i] = -1 t = [i + 1] while j != i: t.append(j + 1) last = j j = a[j] a[last] = -1 ans.append(t) print(len(ans)) for i in range(len(ans)): print(len(ans[i]), *ans[i]) ```
output
1
106,693
12
213,387
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
instruction
0
106,694
12
213,388
Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) a = input().split() a = [(int(a[i]), i) for i in range(n)] a.sort() start = 0 used = set() b = [] while start < n: t = [] cur = start first = True while cur != start or first: first = False t.append(cur+1) used.add(cur) cur = a[cur][1] b.append(t) while start in used: start += 1 print(len(b)) for t in b: print(len(t), end=' ') print(*t) ```
output
1
106,694
12
213,389
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
instruction
0
106,695
12
213,390
Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` import sys input = sys.stdin.readline from collections import defaultdict class Unionfind: def __init__(self, n): self.par = [-1]*n self.rank = [1]*n def root(self, x): p = x while not self.par[p]<0: p = self.par[p] while x!=p: tmp = x x = self.par[x] self.par[tmp] = p return p def unite(self, x, y): rx, ry = self.root(x), self.root(y) if rx==ry: return False if self.rank[rx]<self.rank[ry]: rx, ry = ry, rx self.par[rx] += self.par[ry] self.par[ry] = rx if self.rank[rx]==self.rank[ry]: self.rank[rx] += 1 def is_same(self, x, y): return self.root(x)==self.root(y) def count(self, x): return -self.par[self.root(x)] n = int(input()) a = list(map(int, input().split())) b = a[:] b.sort() d = defaultdict(int) for i in range(n): d[b[i]] = i uf = Unionfind(n) for i in range(n): uf.unite(i, d[a[i]]) ans = defaultdict(list) for i in range(n): ans[uf.root(i)].append(i) print(len(list(ans.keys()))) for l in ans.values(): print(len(l), *list(map(lambda x: x+1, l))) ```
output
1
106,695
12
213,391
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` from sys import stdin n = int(stdin.readline().strip()) a = list(map(int, stdin.readline().strip().split())) a = [(a[i], i+1) for i in range(n)] a.sort(key=lambda x: x[0]) used = [False]*(n+1) ss = [] for i in range(1, n+1): if not used[i]: s = [i] used[i] = True j = i while True: j = a[j-1][1] if not used[j]: s.append(j) used[j] = True else: break ss.append(s) print(len(ss)) for s in ss: print(len(s), ' '.join(list(map(str, s)))) ```
instruction
0
106,696
12
213,392
Yes
output
1
106,696
12
213,393
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` from sys import stdin input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) n=I();v=[1]*n a=list(R());d={} for i,j in enumerate(sorted(a)):d[j]=i ans=[] for i in a: p=d[i] if v[p]: ans+=[], while v[p]: ans[-1]+=p+1, v[p]=0 p=d[a[p]] print(len(ans)) for i in ans: print(len(i),*i) ```
instruction
0
106,697
12
213,394
Yes
output
1
106,697
12
213,395
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n=int(input()) anss=0 a=list(map(int,input().split())) b=[] for i in range(n): b.append([i,a[i],0]) b=sorted(b,key = lambda a : a[1]) for i in range(n): b[i].append(i) b=sorted(b,key = lambda a : a[0]) for i in range(n): if b[i][2]!=1: j=i anss=anss+1 while b[j][2]!=1: b[j][2]=b[j][2]+1 j=b[j][3] print(anss) for i in range(n): if b[i][2]!=2: c=[] ans=0 j=i p=[] while b[j][2]!=2: b[j][2]=b[j][2]+1 p.append(str(j+1)) ans=ans+1 j=b[j][3] print(str(len(p))+" "+" ".join(p)) ```
instruction
0
106,698
12
213,396
Yes
output
1
106,698
12
213,397
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) a = sorted((a[i], i) for i in range(n)) s = [] for i in range(n): if a[i]: l = [] s.append(l) while a[i]: l.append(i + 1) a[i], i = None, a[i][1] print(len(s)) for l in s: print(len(l), *l) ```
instruction
0
106,699
12
213,398
Yes
output
1
106,699
12
213,399
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` from sys import stdin, stdout n = int(stdin.readline().rstrip()) a = [int(x) for x in stdin.readline().rstrip().split()] sorted_position = {} sortat = sorted(a) for i in range(n): sorted_position[sortat[i]] = i all_set = set() for i in range(n): crt_set = set() if i not in all_set: crt_set.add(i) all_set.add(i) next_pos = sorted_position[a[i]] next_elem = a[next_pos] while next_pos not in crt_set: crt_set.add(next_pos) all_set.add(next_pos) next_pos = sorted_position[next_elem] next_elem = a[next_pos] print(len(crt_set), end=' ') for e in crt_set: print(e+1, end=' ') print() ```
instruction
0
106,700
12
213,400
No
output
1
106,700
12
213,401
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` visit=[0 for i in range(100002)] visi2=[0 for i in range(100002)] class Graph(object): def __init__(self, graph_dict=None): """ initializes a graph object If no dictionary or None is given, an empty dictionary will be used """ if graph_dict == None: graph_dict = {} self.num_vertices = 0 else: self.num_vertices = len(graph_dict) self.__graph_dict = graph_dict def vertices(self): """ returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): """ returns the edges of a graph """ return self.__generate_edges() def add_vertex(self, vertex): """ If the vertex "vertex" is not in self.__graph_dict, a key "vertex" with an empty list as a value is added to the dictionary. Otherwise nothing has to be done. """ if vertex not in self.__graph_dict: self.__graph_dict[vertex] = [] self.num_vertices += 1 def add_edge(self, edge): """ assumes that edge is of type set, tuple or list; between two vertices can be multiple edges! """ #assuming vertex1 is FROMvertex and vertex2 is TOvertex edge=set(edge) (vertex1, vertex2) = tuple(edge) if (vertex1 not in self.__graph_dict): self.add_vertex(vertex1) if (vertex2 not in self.__graph_dict): self.add_vertex(vertex2) if vertex1 in self.__graph_dict: if vertex2 not in self.__graph_dict[vertex1]: self.__graph_dict[vertex1].append(vertex2) #vertex already exists if vertex2 in self.__graph_dict: if vertex1 not in self.__graph_dict[vertex2]: self.__graph_dict[vertex2].append(vertex1) def __generate_edges(self): """ A static method generating the edges of the graph "graph". Edges are represented as sets with one (a loop back to the vertex) or two vertices """ edges = [] for vertex in self.__graph_dict: for neighbour in self.__graph_dict[vertex]: if {neighbour, vertex} not in edges: edges.append({vertex, neighbour}) return edges def find_path(self, start_vertex, end_vertex, path=[]): """ find a path from start_vertex to end_vertex in graph """ graph = self.__graph_dict path = path + [start_vertex] if start_vertex == end_vertex: return path if start_vertex not in graph: return None for vertex in graph[start_vertex]: if vertex not in path: extended_path = self.find_path(vertex, end_vertex, path) if extended_path: return extended_path return None def BFS(self, s): graph = self.__graph_dict visited = [False] * (len(graph)) queue = [] arr = [] i = 0 queue.append(s) visited[i] = True i+=1 while queue: s = queue.pop(0) arr.append(s) print(s, end=" ") for adj in graph[s]: if adj in arr: if visited[arr.index(adj)] == False: queue.append(adj) visited[adj] = True else: queue.append(adj) visited[i] = True i+=1 def DFS(self, s): graph = self.__graph_dict visited = [False] * (len(graph)) stack = [] arr=[] stack.append(s) i=0 visited[i] = True i+=1 while stack: s = stack.pop() arr.append(s) print(s, end=" ") for adj in graph[s]: if adj in arr: if visited[arr.index(adj)] == False: stack.append(adj) visited[adj] = True else: stack.append(adj) visited[i] = True i+=1 def find_all_paths(self, start_vertex, end_vertex, path=[]): """ find all paths from start_vertex to end_vertex in graph """ graph = self.__graph_dict path = path + [start_vertex] if start_vertex == end_vertex: return [path] if start_vertex not in graph: return [] paths = [] for vertex in graph[start_vertex]: if vertex not in path: extended_paths = self.find_all_paths(vertex, end_vertex, path) for p in extended_paths: paths.append(p) return paths def is_connected(self,vertices_encountered=None,start_vertex=None): """ determines if the graph is connected """ if vertices_encountered is None: vertices_encountered = set() gdict = self.__graph_dict vertices = gdict.keys() if not start_vertex: # chosse a vertex from graph as a starting point start_vertex = vertices[0] vertices_encountered.add(start_vertex) if len(vertices_encountered) != len(vertices): for vertex in gdict[start_vertex]: if vertex not in vertices_encountered: if self.is_connected(vertices_encountered, vertex): return True else: return True return False def vertex_degree(self, vertex): """ The degree of a vertex is the number of edges connecting it, i.e. the number of adjacent vertices. Loops are counted double, i.e. every occurence of vertex in the list of adjacent vertices. """ adj_vertices = self.__graph_dict[vertex] degree = len(adj_vertices) + adj_vertices.count(vertex) return degree def degree_sequence(self): """ calculates the degree sequence """ seq = [] for vertex in self.__graph_dict: seq.append(self.vertex_degree(vertex)) seq.sort(reverse=True) return tuple(seq) @staticmethod def is_degree_sequence(sequence): """ Method returns True, if the sequence "sequence" is a degree sequence, i.e. a non-increasing sequence. Otherwise False is returned. """ # check if the sequence sequence is non-increasing: return all(x >= y for x, y in zip(sequence, sequence[1:])) def delta(self): """ the minimum degree of the vertices """ min = 100000000 for vertex in self.__graph_dict: vertex_degree = self.vertex_degree(vertex) if vertex_degree < min: min = vertex_degree return min def Delta(self): """ the maximum degree of the vertices """ max = 0 for vertex in self.__graph_dict: vertex_degree = self.vertex_degree(vertex) if vertex_degree > max: max = vertex_degree return max def density(self): """ method to calculate the density of a graph """ g = self.__graph_dict V = len(g.keys()) E = len(self.edges()) return 2.0 * E / (V * (V - 1)) def diameter(self): """ calculates the diameter of the graph """ v = self.vertices() pairs = [(v[i], v[j]) for i in range(len(v) - 1) for j in range(i + 1, len(v))] smallest_paths = [] for (s, e) in pairs: paths = self.find_all_paths(s, e) smallest = sorted(paths, key=len)[0] smallest_paths.append(smallest) smallest_paths.sort(key=len) # longest path is at the end of list, # i.e. diameter corresponds to the length of this path diameter = len(smallest_paths[-1]) return diameter def DFSnew(self, s): graph = self.__graph_dict stack = [] stack.append(s) visit[1]=1 co=1 k=[] ans=[] while stack: co+=1 s=stack.pop() visi2[s]+=1 k.append(s) visit[s]+=1 for adj in graph[s]: if visit[adj] == 0: stack.append(adj) visit[adj] = 1 ans.append(co-1) ans+=k return ans sol=[] import copy graph=dict() g=Graph(graph) n=int(input()) a=list(map(int,input().split(" "))) b=copy.deepcopy(a) b.sort() for i in range(n): ind=b.index(a[i]) if ind!=i: g.add_vertex(i+1) g.add_vertex(ind+1) g.add_edge({i+1,ind+1}) else: g.add_vertex(i+1) for iter in graph: if visi2[iter]==0: sol.append(g.DFSnew(iter)) for i in sol: for k in i: print(k,end=" ") print("\n") ```
instruction
0
106,701
12
213,402
No
output
1
106,701
12
213,403
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n = int(input()) a=[0 for j in range (n)] s = input().split() for i in range(n): a[i] = int(s[i]) b = a.copy() b.sort(); ind_orig = {} #store index from orig array for i in range(n): ind_orig[a[i]] = i #for actual comparing permutations ind_perm = [0 for i in range(n)] for i in range(n): ind_perm[i] = ind_orig[b[i]] visited = [False for j in range(n)] lists = [] #indexes from 0 to n-1; elements 0 to n - 1 def make_perm(): for i in range(n): if (visited[i]): continue t = [] t.append(ind_perm[i]) first = i k = i; visited[ind_perm[k]] = True while (ind_perm[k] != first): k = ind_perm[k]; visited[ind_perm[k]] = True t.append(ind_perm[k]) lists.append(t) make_perm() #make elements from indeces def print_res(): for i in range(len(lists)): print(len(lists[i]),end = " ") for j in range(len(lists[i])): print(lists[i][j]+1,end = " ") print() print_res() ```
instruction
0
106,702
12
213,404
No
output
1
106,702
12
213,405
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n = int(input()) d = list(map(int, input().split())) p = [(x, i) for i, x in enumerate(d)] p.sort() used = set() for x, i in p: temp = [] while x not in used: used.add(x) temp.append(i + 1) x, i = p[i] if temp: print(len(temp), end = ' ') for x in temp: print(x, end = ' ') print() ```
instruction
0
106,703
12
213,406
No
output
1
106,703
12
213,407
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
instruction
0
106,704
12
213,408
Tags: flows Correct Solution: ``` import sys readline = sys.stdin.readline from heapq import heappop as hpp, heappush as hp class MinCostFlowwithDijkstra: INF = 1<<60 def __init__(self, N): self.N = N self.Edge = [[] for _ in range(N)] def add_edge(self, st, en, cap, cost): self.Edge[st].append([en, cap, cost, len(self.Edge[en])]) self.Edge[en].append([st, 0, -cost, len(self.Edge[st])-1]) def get_mf(self, so, si, fl): N = self.N INF = self.INF res = 0 Pot = [0]*N geta = N prv = [None]*N prenum = [None]*N while fl: dist = [INF]*N dist[so] = 0 Q = [so] while Q: cost, vn = divmod(hpp(Q), geta) if dist[vn] < cost: continue for enum in range(len(self.Edge[vn])): vf, cap, cost, _ = self.Edge[vn][enum] cc = dist[vn] + cost - Pot[vn] + Pot[vf] if cap > 0 and dist[vf] > cc: dist[vf] = cc prv[vf] = vn prenum[vf] = enum hp(Q, cc*geta + vf) if dist[si] == INF: return -1 for i in range(N): Pot[i] -= dist[i] cfl = fl vf = si while vf != so: cfl = min(cfl, self.Edge[prv[vf]][prenum[vf]][1]) vf = prv[vf] fl -= cfl res -= cfl*Pot[si] vf = si while vf != so: e = self.Edge[prv[vf]][prenum[vf]] e[1] -= cfl self.Edge[vf][e[3]][1] += cfl vf = prv[vf] return res N, Q = map(int, readline().split()) T = MinCostFlowwithDijkstra(2*N+2) geta = N candi = [set(range(N)) for _ in range(N)] for _ in range(Q): t, l, r, v = map(int, readline().split()) l -= 1 r -= 1 v -= 1 if t == 1: for vn in range(l, r+1): for i in range(v-1, -1, -1): if i in candi[vn]: candi[vn].remove(i) else: for vn in range(l, r+1): for i in range(v+1, N): if i in candi[vn]: candi[vn].remove(i) if not all(candi): print(-1) else: source = 2*N sink = 2*N + 1 for i in range(N): T.add_edge(source, i, 1, 0) for v in candi[i]: T.add_edge(i, geta+v, 1, 0) for j in range(N): T.add_edge(i+geta, sink, 1, 2*j+1) print(T.get_mf(source, sink, N)) ```
output
1
106,704
12
213,409
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
instruction
0
106,705
12
213,410
Tags: flows Correct Solution: ``` import sys def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] AUX = [] feasible = True for x in range(n): for p in inter: if p[0] == x: AUX.append(p[1]) while AUX and min(AUX) < x: AUX.remove(min(AUX)) for quantity in range(cnt[x]): if AUX: AUX.remove(min(AUX)) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False for x in range(n-1,-1,-1): for y in range(n-1,-1,-1): if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
output
1
106,705
12
213,411
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
instruction
0
106,706
12
213,412
Tags: flows Correct Solution: ``` import sys def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] right = [] feasible = True for x in range(n): for p in inter: if p[0] == x: right.append(p[1]) while right and min(right) < x: right.remove(min(right)) for quantity in range(cnt[x]): if right: right.remove(min(right)) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:0 for x in range(n)} for y in range(n): for x in range(n): if cnt[x] == y: cnt[x] += 1 if not is_feasible(cnt,L,R): cnt[x] -= 1 ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
output
1
106,706
12
213,413
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
instruction
0
106,707
12
213,414
Tags: flows Correct Solution: ``` from collections import deque from heapq import heappop, heappush class Edge(object): __slots__ = ('x', 'y', 'cap', 'cost', 'inv') def __repr__(self): return f'{self.x}-->{self.y} ({self.cap} , {self.cost})' class MCFP(): def __init__(self): self.G = [] def add(self, x, y, cap, cost): G = self.G G.extend(([] for i in range(max(0,max(x,y)+1-len(G))))) e = Edge() e.x=x ; e.y=y; e.cap=cap; e.cost=cost z = Edge() z.x=y ; z.y=x; z.cap=0; z.cost=-cost e.inv=z ; z.inv=e G[x].append(e) G[y].append(z) def solve(self, src, tgt, inf=float('inf')): n, G = len(self.G), self.G flowVal = flowCost = 0 phi = [0]*n prev = [None]*n inQ = [0]*n cntQ = 1 dist = [inf]*n while 1: self.shortest(src, phi, prev, inQ, dist, inf, cntQ) if prev[tgt] == None: break z = inf x = tgt while x!=src: e = prev[x] z = min(z, e.cap) x = e.x x = tgt while x!=src: e = prev[x] e.cap -= z e.inv.cap += z x = e.x flowVal += z flowCost += z * (dist[tgt] - phi[src] + phi[tgt]) for i in range(n): if prev[i] != None: phi[i] += dist[i] dist[i] = inf cntQ += 1 prev[tgt] = None return flowVal, flowCost def shortest(self, src, phi, prev, inQ, dist, inf, cntQ): n, G = len(self.G), self.G Q = [(dist[src],src)] inQ[src] = cntQ dist[src] = 0 while Q: _, x = heappop(Q) inQ[x] = 0 dx = dist[x]+phi[x] for e in G[x]: y = e.y dy = dx + e.cost - phi[y] if e.cap > 0 and dy < dist[y]: dist[y] = dy prev[y] = e if inQ[y] != cntQ: inQ[y] = cntQ heappush(Q, (dy, y)) return dist, prev def __repr__(self): n, G = len(self.G), self.G s = [] for i in range(n): s.append(' G[{}]:'.format(i)) s.append('\n'.join(' {}'.format(e) for e in G[i])) return '\n'.join(s) import sys ints = (int(x) for x in sys.stdin.read().split()) sys.setrecursionlimit(3000) def main(): n, q = (next(ints) for i in range(2)) leq = [n-1]*n geq = [0]*n for q in range(q): t,l,r,v = (next(ints) for i in range(4)) for i in range(l-1, r): if t==1: geq[i] = max(geq[i], v-1) if t==2: leq[i] = min(leq[i], v-1) imp = any(geq[i]>leq[i] for i in range(n)) if imp: ans = -1 else: src = 2*n+n*n tgt = 2*n+n*n+1 G = MCFP() for i in range(n): G.add(src, i, 1, 0) for i in range(n): for j in range(geq[i], leq[i]+1): G.add(i, j+n, 1, 0) for i in range(n): for j in range(n): G.add(i+n, 2*n+i*n+j, 1, 0) G.add(2*n+i*n+j, tgt, 1, 2*j+1) _, ans = G.solve(src, tgt) #print(G) #print(leq, geq) print(ans) return main() ```
output
1
106,707
12
213,415
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
instruction
0
106,708
12
213,416
Tags: flows Correct Solution: ``` import sys def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] AUX = [] feasible = True for x in range(n): for p in inter: if p[0] == x: AUX.append(p[1]) while AUX and min(AUX) < x: AUX.remove(min(AUX)) for quantity in range(cnt[x]): if AUX: AUX.remove(min(AUX)) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False for x in range(n): for y in range(n): if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
output
1
106,708
12
213,417
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
instruction
0
106,709
12
213,418
Tags: flows Correct Solution: ``` #~ # MAGIC CODEFORCES PYTHON FAST IO import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) #~ # END OF MAGIC CODEFORCES PYTHON FAST IO class Arista(): def __init__(self,salida,llegada,capacidad,flujo,costo,indice): self.salida = salida self.llegada = llegada self.capacidad = capacidad self.flujo = flujo self.costo = costo self.indice = indice def __str__(self): s = "" s = s + "salida =" + str(self.salida) + "\n" s = s + "llegada =" + str(self.llegada) + "\n" s = s + "capacidad =" + str(self.capacidad) + "\n" s = s + "flujo =" + str(self.flujo) + "\n" s = s + "costo =" + str(self.costo) + "\n" s = s + "indice =" + str(self.indice) + "\n" s = s + "------------" return s class Red(): ## Representacion de una Red de flujo ## def __init__(self,s,t): # Crea una red vacio self.lista_aristas = [] self.lista_adyacencia = {} self.vertices = set() self.fuente = s self.sumidero = t def agregar_vertice(self,vertice): self.vertices.add(vertice) def agregar_arista(self,arista): self.vertices.add(arista.salida) self.vertices.add(arista.llegada) self.lista_aristas.append(arista) if arista.salida not in self.lista_adyacencia: self.lista_adyacencia[arista.salida] = set() self.lista_adyacencia[arista.salida].add(arista.indice) def agregar_lista_aristas(self,lista_aristas): for arista in lista_aristas: self.agregar_arista(arista) def cantidad_de_vertices(self): return len(self.vertices) def vecinos(self,vertice): if vertice not in self.lista_adyacencia: return set() else: return self.lista_adyacencia[vertice] def buscar_valor_critico(self,padre): INFINITO = 1000000000 valor_critico = INFINITO actual = self.sumidero while actual != self.fuente: arista_camino = self.lista_aristas[padre[actual]] valor_critico = min(valor_critico,arista_camino.capacidad - arista_camino.flujo) actual = arista_camino.salida return valor_critico def actualizar_camino(self,padre,valor_critico): actual = self.sumidero costo_actual = 0 while actual != self.fuente: self.lista_aristas[padre[actual]].flujo += valor_critico self.lista_aristas[padre[actual]^1].flujo -= valor_critico costo_actual += valor_critico*self.lista_aristas[padre[actual]].costo actual = self.lista_aristas[padre[actual]].salida return costo_actual,True def camino_de_aumento(self): INFINITO = 1000000000 distancia = {v:INFINITO for v in self.vertices} padre = {v:-1 for v in self.vertices} distancia[self.fuente] = 0 #~ for iteracion in range(len(self.vertices)-1): #~ for arista in self.lista_aristas: #~ if arista.flujo < arista.capacidad and distancia[arista.salida] + arista.costo < distancia[arista.llegada]: #~ distancia[arista.llegada] = distancia[arista.salida] + arista.costo #~ padre[arista.llegada] = arista.indice capa_actual,capa_nueva = set([self.fuente]),set() while capa_actual: for v in capa_actual: for arista_indice in self.vecinos(v): arista = self.lista_aristas[arista_indice] if arista.flujo < arista.capacidad and distancia[arista.salida] + arista.costo < distancia[arista.llegada]: distancia[arista.llegada] = distancia[arista.salida] + arista.costo padre[arista.llegada] = arista.indice capa_nueva.add(arista.llegada) capa_actual = set() capa_actual,capa_nueva = capa_nueva,capa_actual if distancia[self.sumidero] < INFINITO: valor_critico = self.buscar_valor_critico(padre) costo_actual,hay_camino = self.actualizar_camino(padre,valor_critico) return valor_critico,costo_actual,hay_camino else: return -1,-1,False def max_flow_min_cost(self): flujo_total = 0 costo_total = 0 hay_camino = True while hay_camino: #~ for x in self.lista_aristas: #~ print(x) flujo_actual,costo_actual,hay_camino = self.camino_de_aumento() if hay_camino: flujo_total += flujo_actual costo_total += costo_actual return flujo_total,costo_total INFINITO = 10000000000000 n,q = map(int,input().split()) maxi = [n for i in range(n)] mini = [1 for i in range(n)] R = Red(0,2*n+1) prohibidos = {i:set() for i in range(n)} for i in range(n): for k in range(n+1): R.agregar_arista(Arista(R.fuente,i+1,1,0,2*k+1,len(R.lista_aristas))) R.agregar_arista(Arista(i+1,R.fuente,0,0,-2*k-1,len(R.lista_aristas))) for j in range(n): R.agregar_arista(Arista(n+j+1,R.sumidero,1,0,0,len(R.lista_aristas))) R.agregar_arista(Arista(R.sumidero,n+j+1,0,0,0,len(R.lista_aristas))) for z in range(q): t,l,r,v = map(int,input().split()) if t == 1: for i in range(v-1): for j in range(l,r+1): prohibidos[i].add(j) else: for i in range(v,n): for j in range(l,r+1): prohibidos[i].add(j) for i in range(n): for j in range(mini[i],maxi[i]+1): if j not in prohibidos[i]: R.agregar_arista(Arista(i+1,n+j,1,0,0,len(R.lista_aristas))) R.agregar_arista(Arista(n+j,i+1,0,0,0,len(R.lista_aristas))) flujo_total,costo_total = R.max_flow_min_cost() #~ print(flujo_total,costo_total) if flujo_total < n: print("-1") else: print(costo_total) ```
output
1
106,709
12
213,419
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
instruction
0
106,710
12
213,420
Tags: flows Correct Solution: ``` import sys def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] AUX = [] feasible = True for x in range(n): for p in inter: if p[0] == x: AUX.append(p[1]) while AUX and min(AUX) < x: AUX.remove(min(AUX)) for quantity in range(cnt[x]): if AUX: AUX.remove(min(AUX)) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False for x in range(n): for y in range(n): if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair if had_pair: break if had_pair: break ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
output
1
106,710
12
213,421
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
instruction
0
106,711
12
213,422
Tags: flows Correct Solution: ``` import sys from random import seed,shuffle seed(25) def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] AUX = [] feasible = True for x in range(n): for p in inter: if p[0] == x: AUX.append(p[1]) while AUX and min(AUX) < x: AUX.remove(min(AUX)) for quantity in range(cnt[x]): if AUX: AUX.remove(min(AUX)) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False AUX = list(range(n)) shuffle(AUX) for x in AUX: AUX_2 = list(range(n)) shuffle(AUX_2) for y in AUX_2: if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
output
1
106,711
12
213,423
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1 Submitted Solution: ``` import sys def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] right = [] feasible = True for x in range(n): for p in inter: if p[0] == x: right.append(p[1]) while right and min(right) < x: right.remove(min(right)) for quantity in range(cnt[x]): if right: right.remove(min(right)) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False for x in range(n): for y in range(n): if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
instruction
0
106,712
12
213,424
Yes
output
1
106,712
12
213,425
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1 Submitted Solution: ``` import sys def is_feasible(cnt,L,R): n = len(R) inter = sorted([(L[i],R[i]) for i in range(n)]) feasible = True for x in range(n): for quantity in range(cnt[x]): AUX = [p for p in inter if p[0] <= x <= p[1]] if AUX: best = AUX[0] for w in AUX: if w[0] > best[0]: best = w elif w[0] == best[0] and w[1] < best[1]: best = w inter.remove(w) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False for x in range(n): for y in range(n): if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
instruction
0
106,713
12
213,426
No
output
1
106,713
12
213,427
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1 Submitted Solution: ``` import sys n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: A = L[:] cnt = {x:A.count(x) for x in range(n)} has_pair = True while has_pair: has_pair = False for k in range(n): for x in range(n): if A[k] != x and cnt[A[k]] > cnt[x] + 1 and L[k] <= x and x <= R[k]: cnt[A[k]] -= 1 A[k] = x cnt[A[k]] += 1 has_pair = True ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
instruction
0
106,714
12
213,428
No
output
1
106,714
12
213,429
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1 Submitted Solution: ``` import sys def is_feasible(cnt,L,R): n = len(R) inter = sorted([(L[i],R[i]) for i in range(n)]) feasible = True for x in range(n): for quantity in range(cnt[x]): AUX = [p for p in inter if p[0] <= x <= p[1]] if AUX: best = AUX[0] for w in AUX: if w[1] < best[1]: best = w inter.remove(w) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False for x in range(n): for y in range(n): if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
instruction
0
106,715
12
213,430
No
output
1
106,715
12
213,431
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi β€” for each x such that li ≀ x ≀ ri ax β‰₯ vi; * 2 li ri vi β€” for each x such that li ≀ x ≀ ri ax ≀ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≀ n ≀ 50, 0 ≀ q ≀ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n, 1 ≀ vi ≀ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1 Submitted Solution: ``` import sys def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] AUX = [] feasible = True for x in range(n): for p in inter: if p[0] == x: AUX.append(p[1]) # ~ while AUX and min(AUX) < i: # ~ AUX.remove(min(AUX)) # ~ for quantity in range(cnt[x]): # ~ if AUX: # ~ AUX.remove(min(AUX)) # ~ else: # ~ feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False for x in range(n): for y in range(n): if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
instruction
0
106,716
12
213,432
No
output
1
106,716
12
213,433
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code: int fast_max(int n, int a[]) { int ans = 0; int offset = 0; for (int i = 0; i < n; ++i) if (ans < a[i]) { ans = a[i]; offset = 0; } else { offset = offset + 1; if (offset == k) return ans; } return ans; } That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer. Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109 + 7. Input The only line contains two integers n and k (1 ≀ n, k ≀ 106), separated by a space β€” the length of the permutations and the parameter k. Output Output the answer to the problem modulo 109 + 7. Examples Input 5 2 Output 22 Input 5 3 Output 6 Input 6 3 Output 84 Note Permutations from second example: [4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5]. Submitted Solution: ``` from math import factorial n, k = map(int, input().split()) const1 = factorial(n - 2) % (10 ** 9 + 7) const2 = ((n - k - 1) * (n - k) // 2) % (10 ** 9 + 7) const3 = ((const1 // (n - 2)) * (n - k - 2) * 2) % (10 ** 9 + 7) if const3 > 0: ans = (const1 * const2 + const3) % (10 ** 9 + 7) else: ans = (const1 * const2) % (10 ** 9 + 7) print(ans) ```
instruction
0
106,717
12
213,434
No
output
1
106,717
12
213,435
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code: int fast_max(int n, int a[]) { int ans = 0; int offset = 0; for (int i = 0; i < n; ++i) if (ans < a[i]) { ans = a[i]; offset = 0; } else { offset = offset + 1; if (offset == k) return ans; } return ans; } That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer. Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109 + 7. Input The only line contains two integers n and k (1 ≀ n, k ≀ 106), separated by a space β€” the length of the permutations and the parameter k. Output Output the answer to the problem modulo 109 + 7. Examples Input 5 2 Output 22 Input 5 3 Output 6 Input 6 3 Output 84 Note Permutations from second example: [4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5]. Submitted Solution: ``` inp = input() parts = inp.split() n = int(parts[0]) k = int(parts[1]) mod = 1000000007 fact = [None] * 1000001 fact[0] = 1 fact[1] = 1 for i in range(2, 1000001): fact[i] = (fact[i-1] * i) % mod # n - οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ # m - οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½, οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ (οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½) # οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ k οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ < m seen = [0] * n for m in range(k + 1, n): #οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ m add_seen = [0] * n #οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½ seen οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ m for pos_m in range (0, m - k): #οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ m # οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½ pos_m οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ < m # οΏ½ οΏ½οΏ½ k οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½ pos_m οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ < m # οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ nperm - οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ (pos_m - 1 + k) οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ m-1 οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ nperm = fact[m-1] / fact[m - 1 - pos_m - k] # οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ nremain = fact[n - pos_m - k - 1] #οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½, οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ p < m οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ [0, pos_m - k) sumseen = 0 if pos_m > k: sumseen = sum(seen[0:pos_m-k]) add_seen[pos_m] = (((nperm * nremain) % mod) - sumseen) % mod for i in range(0, n): seen[i] += add_seen[i] print (sum(seen)) ```
instruction
0
106,718
12
213,436
No
output
1
106,718
12
213,437
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code: int fast_max(int n, int a[]) { int ans = 0; int offset = 0; for (int i = 0; i < n; ++i) if (ans < a[i]) { ans = a[i]; offset = 0; } else { offset = offset + 1; if (offset == k) return ans; } return ans; } That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer. Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109 + 7. Input The only line contains two integers n and k (1 ≀ n, k ≀ 106), separated by a space β€” the length of the permutations and the parameter k. Output Output the answer to the problem modulo 109 + 7. Examples Input 5 2 Output 22 Input 5 3 Output 6 Input 6 3 Output 84 Note Permutations from second example: [4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5]. Submitted Solution: ``` x=[] s=0 m=0 z=int(0) for i in input().split(): x.append(i) s= s+ int(x[z]) z=z+1 if (s%2)==0: for i in range (6): for j in range (6): for k in range (6): m=m+1 if (i!=k!=j): if (int(x[i])+int(x[j])+int(x[k]))==(s/2): m=0 if m== 216: print('NO') else: print('YES') ```
instruction
0
106,719
12
213,438
No
output
1
106,719
12
213,439
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code: int fast_max(int n, int a[]) { int ans = 0; int offset = 0; for (int i = 0; i < n; ++i) if (ans < a[i]) { ans = a[i]; offset = 0; } else { offset = offset + 1; if (offset == k) return ans; } return ans; } That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer. Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109 + 7. Input The only line contains two integers n and k (1 ≀ n, k ≀ 106), separated by a space β€” the length of the permutations and the parameter k. Output Output the answer to the problem modulo 109 + 7. Examples Input 5 2 Output 22 Input 5 3 Output 6 Input 6 3 Output 84 Note Permutations from second example: [4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5]. Submitted Solution: ``` from math import factorial n,k=map(int,input().split(' ')) h=n s=0 if (n-k)==1: print(1) else: while h-k>1: a=(h-k)*(h-k-1)/2 b=factorial(h-2)*(n-h+1) s+=a*b h-=1 print(int(s)) ```
instruction
0
106,720
12
213,440
No
output
1
106,720
12
213,441
Provide tags and a correct Python 3 solution for this coding contest problem. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
instruction
0
106,753
12
213,506
Tags: bitmasks, constructive algorithms, greedy, implementation Correct Solution: ``` x,d=[int(s) for s in input().split()[:2]] def getd(y): if y<=1: return y da=1 num=0 while da*2<=y: da*=2 num+=1 return num f=1 ans=[] while x>0: num=getd(x) n=2**num-1 for i in range(num): ans.append(f) f+=d+1 x-=n print(len(ans)) for i in ans[:-1]: print(i,end=' ') print(ans[-1]) ```
output
1
106,753
12
213,507
Provide tags and a correct Python 3 solution for this coding contest problem. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
instruction
0
106,754
12
213,508
Tags: bitmasks, constructive algorithms, greedy, implementation Correct Solution: ``` n, d = [int(c) for c in input().split(" ")] n_copy = n groupsize_cases = [2**c - 1 for c in range(100)] groups = [] # print(groupsize_cases[:20]) i = 1 while n >= groupsize_cases[i]: i += 1 # print(groupsize_cases[i]) i -= 1 while n > 0: while n >= groupsize_cases[i]: groups.append(i) n -= groupsize_cases[i] i -= 1 # print(groups) # print(groupsize_cases[max(groups)]) ans = [] current_number = 1 for num in groups: ans.append(current_number) for i in range(num-1): # current_number += 1 ans.append(current_number) current_number += d+1 print(len(ans)) for num in ans: print(num, end = " ") ```
output
1
106,754
12
213,509
Provide tags and a correct Python 3 solution for this coding contest problem. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
instruction
0
106,755
12
213,510
Tags: bitmasks, constructive algorithms, greedy, implementation Correct Solution: ``` X, D = map(int, input().split()) cn = 1 add0 = 1 if (X&1) else 0 ans = [] for i in range(30,0,-1): if not (X & (1<<i)): continue ans += [cn]*i add0 += 1 cn += D for i in range(add0): ans.append(cn) cn += D print(len(ans)) print(' '.join(map(str, ans))) ```
output
1
106,755
12
213,511
Provide tags and a correct Python 3 solution for this coding contest problem. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
instruction
0
106,756
12
213,512
Tags: bitmasks, constructive algorithms, greedy, implementation Correct Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ from math import factorial from collections import Counter, defaultdict from heapq import heapify, heappop, heappush def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) mod = 998244353 INF = float('inf') from math import log2, floor # ------------------------------ def main(): x, d = RL() res = [] now = 1 while x>0: num = floor(log2(x+1)) res+=[now]*num x-=2**num-1 now+=d+1 print(len(res)) print(*res) if __name__ == "__main__": main() ```
output
1
106,756
12
213,513
Provide tags and a correct Python 3 solution for this coding contest problem. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
instruction
0
106,757
12
213,514
Tags: bitmasks, constructive algorithms, greedy, implementation Correct Solution: ``` # -*- coding: UTF-8 -*- s = [2 ** i - 1 for i in range(31, 0, -1)] z = [i for i in range(31, 0, -1)] x, d = map(int, input().split()) st = 1 p = 0 ret = [] while x > 0: while s[p] > x: p += 1 for i in range(z[p]): ret.append(st) st += d x -= s[p] if x != 0: print('-1') else: print(len(ret)) print(' '.join(str(i) for i in ret)) ```
output
1
106,757
12
213,515
Provide tags and a correct Python 3 solution for this coding contest problem. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
instruction
0
106,758
12
213,516
Tags: bitmasks, constructive algorithms, greedy, implementation Correct Solution: ``` x, k = list(map(int,input().split())) tot = 0 now = 1 d = 1 ans = [] def add(am,el): global ans ans += [el]*am def rec(l): global d global tot now = 1 while True: if tot + (2**now - 1) > x: if (tot-len(ans) ) != 0: rec(x-len(ans)) break tot+=(2**now - 1) add(now,d) now+=1 d+=k if tot == x: break rec(x) print(len(ans)) print(*ans) ```
output
1
106,758
12
213,517
Provide tags and a correct Python 3 solution for this coding contest problem. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
instruction
0
106,759
12
213,518
Tags: bitmasks, constructive algorithms, greedy, implementation Correct Solution: ``` #!/usr/bin/env python3 import sys [X, d] = map(int, sys.stdin.readline().strip().split()) a = [] m = 1 - d i = 31 while i > 0: if 2**i - 1 > X: i -= 1 continue a.extend([m + d] * i) m += d X -= 2**i - 1 print (len(a)) print (' '.join(map(str, a))) ```
output
1
106,759
12
213,519
Provide tags and a correct Python 3 solution for this coding contest problem. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
instruction
0
106,760
12
213,520
Tags: bitmasks, constructive algorithms, greedy, implementation Correct Solution: ``` x, d = [int(i) for i in input().split()] cr = 1 ans = [] while x: i = 0 while ((1 << i) - 1) <= x: i += 1 for j in range(i - 1): ans.append(cr) x -= (1 << (i - 1)) - 1 cr += d print(len(ans)) print(*ans) ```
output
1
106,760
12
213,521
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid. Submitted Solution: ``` from math import log2, floor, ceil x, d = input().split() x, d = int(x), int(d) k = 1 arr = list() c = 1 ans = True while (x > 0): p = floor(log2(x)) if (2**(p+1) - 1) <= x: p += 1 if (p == 0): ans = False break arr.extend([k]*p) k += d+1 x -= (2**p - 1) if (ans) and (len(arr) <= 10000): print(len(arr)) print(' '.join(list(map(str, arr)))) else: print(-1) ```
instruction
0
106,761
12
213,522
Yes
output
1
106,761
12
213,523
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid. Submitted Solution: ``` X, d = map(int, input().split()) a = list() cur = 1 for i in range(32): if X&(1<<i): for j in range(i): a.append(cur) cur = cur+d a.append(cur) cur = cur+d print(len(a)) for i in a: print(i, end=" ") ```
instruction
0
106,762
12
213,524
Yes
output
1
106,762
12
213,525
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≀ X, d ≀ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≀ n ≀ 10 000)β€” the number of integers in the final array. Second line should consist of n space separated integers β€” a1, a2, ... , an (1 ≀ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence β‰₯ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid. Submitted Solution: ``` p2 = [(i, 2**i-1) for i in range(1,40)] # print(p2) X, d = map(int, input().split(' ')) lens = [] for i in p2[::-1]: if X >= i[1]: X -= i[1] lens.append(i[0]) # print(lens) # print(X) # if X > 0: # print(-1) # exit(0) el = 1 # if el + len(lens)*d > 10**18: # print(-1) # exit(0) if sum(lens) >= 10000: print(-1) exit(0) print(sum(lens)+X) for i in lens: print((str(el)+' ')*i, end='') el += d for i in range(X): print(el, end=' ') el += d # print(lens) ```
instruction
0
106,763
12
213,526
Yes
output
1
106,763
12
213,527