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
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: * They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i ≠ j either r_i < l_j or r_j < l_i. * For each block the sum of its elements is the same. Formally, $$$a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k].$$$ * The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. <image> The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks. Input The first line contains integer n (1 ≤ n ≤ 1500) — the length of the given array. The second line contains the sequence of elements a[1], a[2], ..., a[n] (-10^5 ≤ a_i ≤ 10^5). Output In the first line print the integer k (1 ≤ k ≤ n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them. Examples Input 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3 Submitted Solution: ``` n = int(input()) lst = list(map(int,input().split())) d,res,summa = {},{},0 for i,y in enumerate(lst): summa+=y s=summa for j in range(i+1): if d.get(s)==None: d[s]=[0,-1] res[s]=[] if d[s][1]<j: d[s][0]+=1 d[s][1]=i res[s].append([j+1,i+1]) s-=lst[j] ans,e = 0,-1 for i,x in enumerate(d): if d[x][0]>ans: ans,e=d[x][0],x print(ans) for i,x in enumerate(res[e]): print(*x) ```
instruction
0
7,623
12
15,246
Yes
output
1
7,623
12
15,247
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: * They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i ≠ j either r_i < l_j or r_j < l_i. * For each block the sum of its elements is the same. Formally, $$$a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k].$$$ * The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. <image> The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks. Input The first line contains integer n (1 ≤ n ≤ 1500) — the length of the given array. The second line contains the sequence of elements a[1], a[2], ..., a[n] (-10^5 ≤ a_i ≤ 10^5). Output In the first line print the integer k (1 ≤ k ≤ n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them. Examples Input 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3 Submitted Solution: ``` from __future__ import print_function,division import os,sys,atexit if sys.version_info[0] < 3: range = xrange from cStringIO import StringIO as BytesIO sys.stdout = BytesIO() else: from io import BytesIO sys.stdout = BytesIO() _write = sys.stdout.write sys.stdout.write = lambda s: _write(s.encode()) atexit.register(lambda: os.write(1, sys.stdout.getvalue())) from collections import defaultdict as dd, deque n = int(input()) A = [int(x) for x in input().split()] cA = [0] for a in A: cA.append(cA[-1] + a) B = dd(list) for l in range(1,n+1): for i in range(n-l+1): s = cA[i+l] - cA[i] B[s].append((i,i+l)) best = 0 bestb = None for b in sorted(B, key=lambda b: len(B[b]), reverse=True): if best > len(B[b]): break A = sorted(B[b], key=lambda x: x[1]) res = 0 lr = -1 for l,r in A: if lr <= l: lr = r res += 1 if res > best: best = res bestb = b print(best) A = sorted(B[bestb], key=lambda x: x[1]) res = 0 lr = -1 for l,r in A: if lr <= l: lr = r res += 1 print(l+1,r) ```
instruction
0
7,624
12
15,248
Yes
output
1
7,624
12
15,249
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: * They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i ≠ j either r_i < l_j or r_j < l_i. * For each block the sum of its elements is the same. Formally, $$$a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k].$$$ * The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. <image> The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks. Input The first line contains integer n (1 ≤ n ≤ 1500) — the length of the given array. The second line contains the sequence of elements a[1], a[2], ..., a[n] (-10^5 ≤ a_i ≤ 10^5). Output In the first line print the integer k (1 ≤ k ≤ n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them. Examples Input 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3 Submitted Solution: ``` from collections import defaultdict n = int(input()) nums = list(map(int, input().split())) freq = defaultdict(list) for i in range(n): for j in range(i+1, n+1): freq[sum(nums[i:j])].append((i+1, j)) ans = [] for k in freq: l = freq[k] l.sort(key=lambda x: x[1]) tmp = [l[0]] for i, j in l: if i <= tmp[-1][1]: continue tmp.append([i, j]) if len(tmp) > len(ans): ans = tmp print (len(ans)) for i, j in ans: print (i, j) ```
instruction
0
7,625
12
15,250
Yes
output
1
7,625
12
15,251
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: * They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i ≠ j either r_i < l_j or r_j < l_i. * For each block the sum of its elements is the same. Formally, $$$a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k].$$$ * The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. <image> The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks. Input The first line contains integer n (1 ≤ n ≤ 1500) — the length of the given array. The second line contains the sequence of elements a[1], a[2], ..., a[n] (-10^5 ≤ a_i ≤ 10^5). Output In the first line print the integer k (1 ≤ k ≤ n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them. Examples Input 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3 Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) 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") #------------------------------------------------------------------------- #mod = 9223372036854775807 class SegmentTree: def __init__(self, data, default=-10**6, func=lambda a, b: max(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) class SegmentTree1: def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) MOD=10**9+7 class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD mod=10**9+7 omod=998244353 #------------------------------------------------------------------------- prime = [True for i in range(50001)] pp=[] def SieveOfEratosthenes(n=50000): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 for i in range(50001): if prime[i]: pp.append(i) #---------------------------------running code------------------------------------------ n=int(input()) a=list(map(int,input().split())) d=defaultdict(list) for i in range (n): s=0 for j in range (i,n): s+=a[j] if len(d[s])==0: d[s].append((i+1,j+1)) else: if d[s][-1][1]<=i: d[s].append((i+1,j+1)) e=sorted(d, key=lambda k: len(d[k]), reverse=True) print(len(d[e[0]])) for i in d[e[0]]: print(*i) ```
instruction
0
7,626
12
15,252
No
output
1
7,626
12
15,253
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: * They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i ≠ j either r_i < l_j or r_j < l_i. * For each block the sum of its elements is the same. Formally, $$$a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k].$$$ * The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. <image> The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks. Input The first line contains integer n (1 ≤ n ≤ 1500) — the length of the given array. The second line contains the sequence of elements a[1], a[2], ..., a[n] (-10^5 ≤ a_i ≤ 10^5). Output In the first line print the integer k (1 ≤ k ≤ n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them. Examples Input 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3 Submitted Solution: ``` # -*- coding: utf-8 -*- # @Time : 2019/3/21 12:10 # @Author : LunaFire # @Email : gilgemesh2012@gmail.com # @File : F2. Same Sum Blocks (Hard).py ```
instruction
0
7,627
12
15,254
No
output
1
7,627
12
15,255
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: * They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i ≠ j either r_i < l_j or r_j < l_i. * For each block the sum of its elements is the same. Formally, $$$a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k].$$$ * The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. <image> The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks. Input The first line contains integer n (1 ≤ n ≤ 1500) — the length of the given array. The second line contains the sequence of elements a[1], a[2], ..., a[n] (-10^5 ≤ a_i ≤ 10^5). Output In the first line print the integer k (1 ≤ k ≤ n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them. Examples Input 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3 Submitted Solution: ``` n=int(input()) arr=list(map(int,input().split())) dp=[[0 for i in range(n)] for j in range(n)] sgn_tree=[{} for j in range(2*n)] maxi=0 ans=0 value=0 d=[{} for i in range(n+1)] maxi=0 for i in range(n-1,-1,-1): for k in d[i+1]: d[i][k] =d[i+1][k] for j in range(n): if j>=i: if i==j: dp[i][j] =arr[i] elif j-i ==1: dp[i][j] =arr[i] +arr[j] else: dp[i][j] =dp[i+1][j-1] + arr[i] +arr[j] value =dp[i][j] v=d[j+1].get(value,0) u=d[i].get(value,0) d[i][value] =max(u-1,v) +1 if v >maxi: maxi =v ans=value i=0 ind_ans=[] while i<n: j=i add=0 while j <n and add <ans: add+= arr[j] j+=1 if add ==ans: if ind_ans: if i+1 <=ind_ans[-1][1]: ind_ans.pop() ind_ans.append([i+1,j]) i+=1 if ans ==0: print(1) print(1,1) else: print(len(ind_ans)) for i in ind_ans: print(i[0],i[1]) ```
instruction
0
7,628
12
15,256
No
output
1
7,628
12
15,257
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a set of blocks (l_1, r_1), (l_2, r_2), ..., (l_k, r_k) such that: * They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i ≠ j either r_i < l_j or r_j < l_i. * For each block the sum of its elements is the same. Formally, $$$a[l_1]+a[l_1+1]+...+a[r_1]=a[l_2]+a[l_2+1]+...+a[r_2]= ... = a[l_k]+a[l_k+1]+...+a[r_k].$$$ * The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), ..., (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. <image> The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks. Input The first line contains integer n (1 ≤ n ≤ 1500) — the length of the given array. The second line contains the sequence of elements a[1], a[2], ..., a[n] (-10^5 ≤ a_i ≤ 10^5). Output In the first line print the integer k (1 ≤ k ≤ n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them. Examples Input 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3 Submitted Solution: ``` n=int(input()) arr=list(map(int,input().split())) dp=[[0 for i in range(n)] for j in range(n)] sgn_tree=[{} for j in range(2*n)] maxi=0 ans=0 value=0 d=[{} for i in range(n+1)] maxi=0 for i in range(n-1,-1,-1): for k in d[i+1]: d[i][k] =d[i+1][k] for j in range(n): if j>=i: if i==j: dp[i][j] =arr[i] elif j-i ==1: dp[i][j] =arr[i] +arr[j] else: dp[i][j] =dp[i+1][j-1] + arr[i] +arr[j] value =dp[i][j] v=d[j+1].get(value,0) u=d[i].get(value,0) d[i][value] =max(u-1,v) +1 if v >maxi: maxi =v ans=value i=0 ind_ans=[] while i<n: j=i add=0 while j <n and add <ans: add+= arr[j] j+=1 if add ==ans: if ind_ans: if i+1 <=ind_ans[-1][1]: ind_ans.pop() ind_ans.append([i+1,j]) i+=1 print(len(ind_ans)) for i in ind_ans: print(i[0],i[1]) ```
instruction
0
7,629
12
15,258
No
output
1
7,629
12
15,259
Provide tags and a correct Python 3 solution for this coding contest problem. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted.
instruction
0
7,703
12
15,406
Tags: dp, greedy, two pointers Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") class seq(): def __init__(self, l, c): self.length = l self.final_ctr = c t = int(input()) for _ in range(t): n = int(input()) d = {} c = {} prev = {} ctr = {} li = [int(i) for i in input().split(' ')] n = len(li) for i in li: ctr[i] = ctr.get(i, 0) + 1 so = sorted(ctr) pp = -1 for i in so: prev[i] = pp pp = i mx = 1 for i in li: if i in d: # i在d内,表示前面出现过i if prev[i] in d and d[prev[i]][1].final_ctr == ctr[prev[i]]: # 前一个元素已选满 if d[prev[i]][1].length > max(d[i][1].length,d[i][0].length): d[i][0].length = d[prev[i]][1].length d[i][0].final_ctr = 0 if c.get(prev[i],0) > max(d[i][1].length,d[i][0].length): # 前一个元素(不一定选满)的计数大于现在的,现在的不选满 d[i][0].length = c[prev[i]] d[i][0].final_ctr = 0 d[i][1].final_ctr += 1 d[i][1].length += 1 d[i][0].final_ctr += 1 d[i][0].length += 1 else: d.setdefault(i,[seq(0,0),seq(0,0)]) if prev[i] in d: if d[prev[i]][1].final_ctr == ctr[prev[i]]: d[i][1] = seq(d[prev[i]][1].length+1, 1) d[i][0] = seq(d[prev[i]][1].length+1, 1) if c.get(prev[i],0) > d[i][1].length: d[i][1].length = c[prev[i]] + 1 d[i][0].length = c[prev[i]] + 1 d[i][1].final_ctr = 1 d[i][0].final_ctr = 1 else: d[i][1] = seq(c[prev[i]]+1, 1) d[i][0] = seq(c[prev[i]]+1, 1) else: d[i][1] = seq(1, 1) mx = max(mx, d[i][1].length,d[i][0].length) c[i] = c.get(i, 0) + 1 print(n-mx) ''' 1 17 0 0 0 0 1 1 1 0 0 0 0 1 1 1 2 2 2 4 and 6 ''' ```
output
1
7,703
12
15,407
Provide tags and a correct Python 3 solution for this coding contest problem. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted.
instruction
0
7,704
12
15,408
Tags: dp, greedy, two pointers Correct Solution: ``` import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 19 MOD = 10 ** 9 + 7 def compress(S): zipped, unzipped = {}, {} for i, a in enumerate(sorted(S)): zipped[a] = i unzipped[i] = a return zipped, unzipped for _ in range(INT()): N = INT() A = LIST() zipped, _ = compress(A) for i in range(N): A[i] = zipped[A[i]] B = [0] * N for i, a in enumerate(A): B[a] = i mx = cnt = 1 for i in range(N-1): if B[i] < B[i+1]: cnt += 1 else: cnt = 1 mx = max(mx, cnt) print(N - mx) ```
output
1
7,704
12
15,409
Provide tags and a correct Python 3 solution for this coding contest problem. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted.
instruction
0
7,705
12
15,410
Tags: dp, greedy, two pointers Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int,input().split())) b = sorted(list(set(a))) max_r = 0 for i in range(n): a[i] = b.index(a[i]) while a!=[]: r = 0 last = a[-1] for i in range(len(a)-1,-1,-1): if a[i] == last or a[i]+1 == last: r += 1 last = a[i] a.pop(i) if r>max_r: max_r = r print(n - max_r) ```
output
1
7,705
12
15,411
Provide tags and a correct Python 3 solution for this coding contest problem. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted.
instruction
0
7,706
12
15,412
Tags: dp, greedy, two pointers Correct Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if True else 1): #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) n = int(input()) a = list(map(int, input().split())) se = sorted(list(set(a))) di = {} for i in range(len(se)): di[se[i]] = i+1 a = [di[k] for k in a] count = [0]*(n+1) for i in a:count[i] += 1 c = [0]*(n+1) seen, now = [-1]*(n+1), [-1]*(n+1) dp = [0]*n ans = 0 for i in range(n): cur = a[i] dp[i] = max(dp[i], c[cur-1] + 1) if seen[cur] != -1: dp[i] = max(dp[i], dp[seen[cur] if seen[cur]!=-1 else 0] + 1) if c[cur-1] == count[cur-1]: dp[i] = max(dp[i], (dp[now[cur-1]if now[cur-1]!=-1 else 0]) + c[cur-1]) c[cur] += 1 seen[cur] = i if now[cur] == -1:now[cur] = i print(n - max(dp)) ```
output
1
7,706
12
15,413
Provide tags and a correct Python 3 solution for this coding contest problem. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted.
instruction
0
7,707
12
15,414
Tags: dp, greedy, two pointers Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) l = list(map(int,input().split())) id = list(zip(l,list(range(n)))) id.sort() val, pos = zip(*id) best = 1 i = 1 count = 1 while True: if i >= n: break if pos[i] > pos[i-1]: count += 1 best = max(count,best) else: count = 1 i += 1 print(n-best) ```
output
1
7,707
12
15,415
Provide tags and a correct Python 3 solution for this coding contest problem. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted.
instruction
0
7,708
12
15,416
Tags: dp, greedy, two pointers Correct Solution: ``` def flyingsort(L): # all elements distinct d = {} for i in range(len(L)): d[L[i]] = i L.sort() prev = -1 run = 0 maxRun = -1 for i in L: if d[i] > prev: run += 1 else: run = 1 maxRun = max(maxRun, run) prev = d[i] return len(L) - maxRun T = int(input()) for i in range(T): N = int(input()) L = list(map(int, input().split(' '))) print(flyingsort(L)) ```
output
1
7,708
12
15,417
Provide tags and a correct Python 3 solution for this coding contest problem. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted.
instruction
0
7,709
12
15,418
Tags: dp, greedy, two pointers Correct Solution: ``` """n=int(input()) a=list(map(int,input().split())) ct=[0]*20 for x in a: for sf in range(20): ct[sf]+=(x>>sf)&1 ans=[0]*n for i in range(20): for j in range(ct[i]): print(ans[j],1<<i,ans[j] | 1<<i) ans[j]|=1<<i print(sum([x**2 for x in ans])) """ """k=int(input()) s='codeforces' i,sm=0,1 l=[1]*10 while sm<k: sm//=l[i] print(sm,l[i]) l[i]+=1 print(l[i]) sm*=l[i] print(sm) i=(i+1)%10 print(l) ans=[s[i]*l[i] for i in range(10)] print(''.join(ans))""" """T =int(input()) for _ in range(T): a=input() if len(a)==2: print(a) else: for i in range(0,len(a),2): print(a[i],end="") print(a[-1])""" """T = int(input()) for _ in range(T): n = int(input()) arr = list(map(int,input().split())) a=b=0 for i in range(n): if i%2 != arr[i]%2: if i%2==0: a+=1 else: b+=1 if a==b: print(a) else: print(-1)""" """T= int(input()) for _ in range(T): n,k = list(map(int,input().split())) a = input() e='0'*k+a+'0'*k f = k*2+1 z=ct=0 for i in e.split('1'): ct+=max((len(i)-k)//(k+1),0) print(ct)""" """for _ in range(int(input())): arr = ['#']+sorted(list(input())) n = int(input()) num = [-1]+[int(i) for i in input().split()] ans = ['#']*(n+1) while 0 in num: zero = [] for i in range(1,n+1): if num[i]==0: zero.append(i) num[i]=-1 #print("zero",zero) while arr.count(arr[-1])<len(zero): p = arr[-1] while p==arr[-1]: arr.pop() #print("arr",arr) p=0 for i in zero: p=ans[i]=arr[-1] #print("ans",ans) while arr[-1]==p: arr.pop() for i in range(1,n+1): if ans[i]=='#': for j in zero: num[i]-=abs(j-i) #print("num",num) print(''.join(ans[1:]))""" """import math import collections for _ in range(int(input())): n,k = map(int, input().split()) s = input() ctr = collections.Counter(s) ans = 0 for i in range(1,n+1): g = math.gcd(i, k) l = i // g #print(i,k,g,l) cnt = sum([(v//l)*l for v in ctr.values()]) #print(cnt) if cnt >= i: ans = i print(ans)""" t= int(input()) for _ in range(t): n = int(input()) arr = list(map(int,input().split())) narr = dict() for i in range(n): narr[arr[i]]=i arr.sort() ct=ans=0 for i in range(n): if i>0 and narr[arr[i]]<narr[arr[i-1]]: ct=0 ct+=1 ans = max(ct,ans) print(n-ans) ```
output
1
7,709
12
15,419
Provide tags and a correct Python 3 solution for this coding contest problem. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted.
instruction
0
7,710
12
15,420
Tags: dp, greedy, two pointers Correct Solution: ``` import sys input = sys.stdin.readline import bisect #1st way for _ in range(int(input())): n = int(input()) a = [int(i) for i in input().split()] b = sorted(a) d = [0]*(n+1) #print(a, b) for i in a: d[b.index(i)] = 1 + max(d[b.index(i)],d[b.index(i)-1]) #print(d) print(n-max(d)) ```
output
1
7,710
12
15,421
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted. Submitted Solution: ``` tt = int(input()) for loop in range(tt): n = int(input()) a = list(map(int,input().split())) ai = [] for i in range(n): ai.append( ( a[i] , i ) ) ai.sort() ind = 0 b = [0] * n #newlist non = [0] * (n+1) #numbers of numbers for i in range(n): if i != 0 and ai[i][0] != ai[i-1][0]: ind += 1 b[ai[i][1]] = ind non[ind] += 1 dp = [0] * (n+1) for i in range(n): dp[b[i]] += max( dp[b[i]] , dp[b[i]-1] + 1) print (n - max(dp)) ```
instruction
0
7,711
12
15,422
Yes
output
1
7,711
12
15,423
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted. Submitted Solution: ``` from collections import defaultdict t = int(input()) for _ in range(t): n = int(input()) l = list(map(int,input().split())) l2 = sorted(list(set(l))) d = defaultdict(int) ind = [[-1]*2 for i in range(len(l2))] num = [0]*len(l2) pos = [0]*len(l2) for i in range(len(l2)): d[l2[i]] = i cl = [-1] for i in range(n): x = d[l[i]] cl.append(x) num[x] += 1 if ind[x][0] == -1: ind[x][0] = i+1 ind[x][1] = i+1 dp = [[0]*3 for i in range(n+1)] for i in range(1,n+1): x = cl[i] dp[i][0] = dp[pos[x]][0] + 1 if x == 0: dp[i][1] = dp[pos[x]][1]+1 else: dp[i][1] = max(dp[pos[x]][1],dp[pos[x-1]][0],dp[pos[x-1]][2])+1 if i == ind[x][1]: dp[i][2] = dp[ind[x][0]][1]+num[x]-1 pos[x] = i ans = 0 for i in dp: ans = max(ans,max(i)) print(n-ans) ```
instruction
0
7,712
12
15,424
Yes
output
1
7,712
12
15,425
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted. Submitted Solution: ``` #!/usr/bin/env python #pyrival orz import os import sys from io import BytesIO, IOBase """ for _ in range(int(input())): n,m=map(int,input().split()) n=int(input()) a = [int(x) for x in input().split()] """ def main(): for _ in range(int(input())): n=int(input()) a = [int(x) for x in input().split()] b = [x for x in a] b.sort() ans=n # print(a) for i in range(len(a)): cnt=0 j=i for y in a: if j < len(b) and y==b[j]: j+=1 cnt+=1 ans=min(ans,n-cnt) # print(b[i],a,cnt) print(ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
instruction
0
7,713
12
15,426
Yes
output
1
7,713
12
15,427
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted. Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = [int(x) for x in input().split()] # find longest subsequence of consecutive numbers indices = {} for i in range(n): indices[a[i]] = i ordered = sorted(a) seq_length = [1]*n for i in range(1, n): if indices[ordered[i-1]] < indices[ordered[i]]: seq_length[i] = seq_length[i-1] + 1 print(n - max(seq_length)) ```
instruction
0
7,714
12
15,428
Yes
output
1
7,714
12
15,429
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted. Submitted Solution: ``` test = [3,5,8,1,7] MAX_N = 3000 def ordenado(arr): for i in range(len(arr)-1): if(arr[i] > arr[i+1]): return False return True def principio(arr,i): temp = arr[:] for p in range(i,0,-1): temp[p] = temp[p-1] temp[0] = arr[i] return temp def final(arr,i): temp = arr[:] for p in range(i,len(arr)-1): temp[p] = temp[p+1] temp[-1] = arr[i] return temp def solve(arr,i,mov): if(i >= len(arr)): return MAX_N if(mov > len(arr) or ordenado(arr)): return mov p = principio(arr,i) f = final(arr,i) mov = min(solve(arr,i+1,mov),solve(p,mov+1,mov+1),solve(f,mov+1,mov+1)) return mov t = int(input()) res = [] for i in range(t): input() # Numero de numeros arr = list(map(int,input().split())) #Numeros res.append(solve(arr,0,0)) for r in res: print(r) # print(principio(test,2)) # print(test) # print(solve(test,0,0)) ```
instruction
0
7,715
12
15,430
No
output
1
7,715
12
15,431
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted. Submitted Solution: ``` from collections import Counter import math import sys from bisect import bisect,bisect_left,bisect_right def input(): return sys.stdin.readline().strip() def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def mod(): return 10**9+7 for i in range(INT()): n = INT() arr = LIST() arr1 = sorted(arr) d = {} ind = 0 for i in arr1: d[i] = ind ind += 1 # print(d) c = [] for i in range(n): c.append(abs(d[arr[i]]-i)) d1 = {} for i in c: if i not in d1: d1[i] = 1 else: d1[i] += 1 ans = 0 for i in d1: ans += d1[i]//2 print(ans) ```
instruction
0
7,716
12
15,432
No
output
1
7,716
12
15,433
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted. Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase import threading from math import floor from bisect import bisect_right from collections import deque from math import gcd mod=998244353 def main(): for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) s=list(set(arr)) s.sort() s=list(zip(s,range(0,n))) ind=dict(s) last_ind=dict() for i in range(n): arr[i]=ind[arr[i]] if arr[i] in last_ind: last_ind[arr[i]]=i else: last_ind[arr[i]]=-1 # print(arr) # print(last_ind) dp=[0]*(len(s)+2) ans=n for i in range(n): # print(i,dp) if last_ind[arr[i]]==i: dp[arr[i]]+=1 else: dp[arr[i]]=1+max(dp[arr[i]],dp[arr[i]-1]) ans=min(ans,n-dp[arr[i]]) # print(dp) print(ans) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
instruction
0
7,717
12
15,434
No
output
1
7,717
12
15,435
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: 1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array; 2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: * after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; * after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order. Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n]. Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a. Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of n for all test cases in one test does not exceed 3000. Output For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order. Example Input 4 5 4 7 2 3 9 5 3 5 8 1 7 5 1 4 5 7 12 4 0 2 1 3 Output 2 2 0 2 Note In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9]. In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8]. In the third test case, the array is already sorted. Submitted Solution: ``` def lengthOfLIS(nums): if not nums: return 0 dp=[1]*len(nums) for i in range(1,len(nums)): for j in range(i): if dp[i]<=dp[j]: if nums[i]>nums[j]: dp[i]=dp[j]+1 return max(dp) t=int(input()) while t>0: n=int(input()) arr=list(map(int,input().split())) print(lengthOfLIS(arr)-1) t-=1 ```
instruction
0
7,718
12
15,436
No
output
1
7,718
12
15,437
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. Examples Input 3 3 1 -1 -1 1 2 1 2 -1 1 Output 3 1 2 Input 2 3 1 2 2 2 5 4 Output 1 3 2 Input 2 3 1 2 3 3 2 1 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) b = [map(int, input().split()) for _ in range(n)] c = [n - x.count(-1) for x in zip(*b)] d = [] for r in b: t = {} for i, x in enumerate(r): if x != -1: if x not in t: t[x] = set() t[x].add(i) d.append([x for i, x in sorted(t.items())][:: -1]) p = [i for i, x in enumerate(c) if not x] for v in d: if v: for x in v[-1]: c[x] -= 1 if not c[x]: p.append(x) r = [] while p: x = p.pop() r.append(x + 1) for i, v in enumerate(d): if v: v[-1].discard(x) if not v[-1]: d[i].pop() if d[i]: for y in d[i][-1]: c[y] -= 1 if not c[y]: p.append(y) print(-1 if len(r) == m else ' '.join(map(str, r))) ```
instruction
0
7,863
12
15,726
No
output
1
7,863
12
15,727
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. Examples Input 3 3 1 -1 -1 1 2 1 2 -1 1 Output 3 1 2 Input 2 3 1 2 2 2 5 4 Output 1 3 2 Input 2 3 1 2 3 3 2 1 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) b = [map(int, input().split()) for _ in range(n)] c = [n - x.count(-1) for x in zip(*b)] d = [] for r in b: t = {} for i, x in enumerate(r): if x != -1: if x not in t: t[x] = set() t[x].add(i) d.append([x for i, x in sorted(t.items())][:: -1]) p = [i for i, x in enumerate(c) if not x] for v in d: if v: for x in v[-1]: c[x] -= 1 if not c[x]: p.append(x) r = [] while p: x = p.pop() r.append(x + 1) for i, v in enumerate(d): if v: v[-1].discard(x) if not v[-1]: d[i].pop() if d[i]: for y in d[i][-1]: c[y] -= 1 if not c[y]: p.append(y) print([-1, ' '.join(map(str, r))][len(r) == m]) ```
instruction
0
7,864
12
15,728
No
output
1
7,864
12
15,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. Examples Input 3 3 1 -1 -1 1 2 1 2 -1 1 Output 3 1 2 Input 2 3 1 2 2 2 5 4 Output 1 3 2 Input 2 3 1 2 3 3 2 1 Output -1 Submitted Solution: ``` print("I AK IOI") ```
instruction
0
7,865
12
15,730
No
output
1
7,865
12
15,731
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. Examples Input 3 3 1 -1 -1 1 2 1 2 -1 1 Output 3 1 2 Input 2 3 1 2 2 2 5 4 Output 1 3 2 Input 2 3 1 2 3 3 2 1 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) b = [] c = [] for _ in range(n): a = [map(int, input().split())] b += a c.append(n-a.count(-1)) c = [n - x.count(-1) for x in zip(*b)] d = [] for r in b: t = {} for i, x in enumerate(r): if x != -1: if x not in t: t[x] = set() t[x].add(i) d.append([x for i, x in sorted(t.items())][:: -1]) p = [i for i, x in enumerate(c) if not x] for v in d: if v: for x in v[-1]: c[x] -= 1 if not c[x]: p.append(x) r = [] while p: x = p.pop() r.append(x + 1) for i, v in enumerate(d): if v: v[-1].discard(x) if not v[-1]: d[i].pop() if d[i]: for y in d[i][-1]: c[y] -= 1 if not c[y]: p.append(y) if len(r) == m: print(-1) else: print(' '.join(map(str, r))) ```
instruction
0
7,866
12
15,732
No
output
1
7,866
12
15,733
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n × m matrix v using the following formula: <image> Vasya wrote down matrix v on a piece of paper and put it in the table. A year later Vasya was cleaning his table when he found a piece of paper containing an n × m matrix w. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix v from those days. Your task is to find out if the matrix w that you've found could have been obtained by following these rules and if it could, then for what numbers k, a1, a2, ..., an, b1, b2, ..., bm it is possible. Input The first line contains integers n and m (1 ≤ n, m ≤ 100), separated by a space — the number of rows and columns in the found matrix, respectively. The i-th of the following lines contains numbers wi, 1, wi, 2, ..., wi, m (0 ≤ wi, j ≤ 109), separated by spaces — the elements of the i-th row of matrix w. Output If the matrix w could not have been obtained in the manner described above, print "NO" (without quotes) in the single line of output. Otherwise, print four lines. In the first line print "YES" (without quotes). In the second line print an integer k (1 ≤ k ≤ 1018). Note that each element of table w should be in range between 0 and k - 1 inclusively. In the third line print n integers a1, a2, ..., an (0 ≤ ai ≤ 1018), separated by spaces. In the fourth line print m integers b1, b2, ..., bm (0 ≤ bi ≤ 1018), separated by spaces. Examples Input 2 3 1 2 3 2 3 4 Output YES 1000000007 0 1 1 2 3 Input 2 2 1 2 2 0 Output YES 3 0 1 1 2 Input 2 2 1 2 2 1 Output NO Note By <image> we denote the remainder of integer division of b by c. It is guaranteed that if there exists some set of numbers k, a1, ..., an, b1, ..., bm, that you could use to make matrix w, then there also exists a set of numbers that meets the limits 1 ≤ k ≤ 1018, 1 ≤ ai ≤ 1018, 1 ≤ bi ≤ 1018 in the output format. In other words, these upper bounds are introduced only for checking convenience purposes.
instruction
0
7,934
12
15,868
Tags: constructive algorithms, math Correct Solution: ``` def ckkk(u,k): listn=[k+u[i][0]-u[0][0] for i in range(n)] listm=[k+u[0][i] for i in range(m)] for i in range(n): for j in range(m): if (listn[i]+listm[j])%k!=u[i][j]: return (None,None) return (listn,listm) (n,m)=input().split(sep=None, maxsplit=2) (n,m)=(int(n),int(m)) u=[0 for j in range(n)] for i in range(n): x=input().split(sep=None, maxsplit=m) u[i]=[int(j) for j in x] maxx=max([max(u[i]) for i in range(n)]) v=[[u[i+1][j]-u[i][j] for j in range(m)] for i in range(n-1)] dic={} divs={} for i in range(n-1): aaa=min(v[i]) bbb=max(v[i]) if aaa==bbb: continue else: divs[(bbb-aaa)]=1 key=0 if len(divs)>2: key=0 elif not divs.keys(): (lista,listb)=ckkk(u,maxx+1) key=maxx+1 else: divs=list(divs.keys()) divs.sort(key=None, reverse=False) if len(divs)==2: if divs[1]//divs[0]==2: if divs[0]>maxx and not key: (lista,listb)=ckkk(u, divs[0]) if lista: key=divs[0] if divs[1]>maxx and not key: (lista,listb)=ckkk(u, divs[1]) if lista: key=divs[1] else: (lista,listb)=ckkk(u, divs[0]) if lista: key=divs[0] if key: print('YES') print(key) lista=[str(i) for i in lista] listb=[str(i) for i in listb] print(' '.join(lista)) print(' '.join(listb)) else: print('NO') ```
output
1
7,934
12
15,869
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n × m matrix v using the following formula: <image> Vasya wrote down matrix v on a piece of paper and put it in the table. A year later Vasya was cleaning his table when he found a piece of paper containing an n × m matrix w. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix v from those days. Your task is to find out if the matrix w that you've found could have been obtained by following these rules and if it could, then for what numbers k, a1, a2, ..., an, b1, b2, ..., bm it is possible. Input The first line contains integers n and m (1 ≤ n, m ≤ 100), separated by a space — the number of rows and columns in the found matrix, respectively. The i-th of the following lines contains numbers wi, 1, wi, 2, ..., wi, m (0 ≤ wi, j ≤ 109), separated by spaces — the elements of the i-th row of matrix w. Output If the matrix w could not have been obtained in the manner described above, print "NO" (without quotes) in the single line of output. Otherwise, print four lines. In the first line print "YES" (without quotes). In the second line print an integer k (1 ≤ k ≤ 1018). Note that each element of table w should be in range between 0 and k - 1 inclusively. In the third line print n integers a1, a2, ..., an (0 ≤ ai ≤ 1018), separated by spaces. In the fourth line print m integers b1, b2, ..., bm (0 ≤ bi ≤ 1018), separated by spaces. Examples Input 2 3 1 2 3 2 3 4 Output YES 1000000007 0 1 1 2 3 Input 2 2 1 2 2 0 Output YES 3 0 1 1 2 Input 2 2 1 2 2 1 Output NO Note By <image> we denote the remainder of integer division of b by c. It is guaranteed that if there exists some set of numbers k, a1, ..., an, b1, ..., bm, that you could use to make matrix w, then there also exists a set of numbers that meets the limits 1 ≤ k ≤ 1018, 1 ≤ ai ≤ 1018, 1 ≤ bi ≤ 1018 in the output format. In other words, these upper bounds are introduced only for checking convenience purposes.
instruction
0
7,935
12
15,870
Tags: constructive algorithms, math Correct Solution: ``` def main(): n, m = map(int, input().split()) l = list(tuple(map(int, input().split())) for _ in range(n)) ma = max(x for _ in l for x in _) bb = l[0] x = bb[0] aa = [_[0] - x for _ in l] err = set(map(abs, filter(None, (a + b - x for a, row in zip(aa, l) for b, x in zip(bb, row))))) if err: k = err.pop() if err or k <= ma: print('NO') return else: k = ma + 1 for i in range(n): aa[i] %= k print('YES') print(k) print(*aa) print(*bb) if __name__ == '__main__': main() ```
output
1
7,935
12
15,871
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n × m matrix v using the following formula: <image> Vasya wrote down matrix v on a piece of paper and put it in the table. A year later Vasya was cleaning his table when he found a piece of paper containing an n × m matrix w. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix v from those days. Your task is to find out if the matrix w that you've found could have been obtained by following these rules and if it could, then for what numbers k, a1, a2, ..., an, b1, b2, ..., bm it is possible. Input The first line contains integers n and m (1 ≤ n, m ≤ 100), separated by a space — the number of rows and columns in the found matrix, respectively. The i-th of the following lines contains numbers wi, 1, wi, 2, ..., wi, m (0 ≤ wi, j ≤ 109), separated by spaces — the elements of the i-th row of matrix w. Output If the matrix w could not have been obtained in the manner described above, print "NO" (without quotes) in the single line of output. Otherwise, print four lines. In the first line print "YES" (without quotes). In the second line print an integer k (1 ≤ k ≤ 1018). Note that each element of table w should be in range between 0 and k - 1 inclusively. In the third line print n integers a1, a2, ..., an (0 ≤ ai ≤ 1018), separated by spaces. In the fourth line print m integers b1, b2, ..., bm (0 ≤ bi ≤ 1018), separated by spaces. Examples Input 2 3 1 2 3 2 3 4 Output YES 1000000007 0 1 1 2 3 Input 2 2 1 2 2 0 Output YES 3 0 1 1 2 Input 2 2 1 2 2 1 Output NO Note By <image> we denote the remainder of integer division of b by c. It is guaranteed that if there exists some set of numbers k, a1, ..., an, b1, ..., bm, that you could use to make matrix w, then there also exists a set of numbers that meets the limits 1 ≤ k ≤ 1018, 1 ≤ ai ≤ 1018, 1 ≤ bi ≤ 1018 in the output format. In other words, these upper bounds are introduced only for checking convenience purposes.
instruction
0
7,936
12
15,872
Tags: constructive algorithms, math Correct Solution: ``` """ Codeforces Contest 289 Div 2 Problem D Author : chaotic_iak Language: Python 3.4.2 """ ################################################### SOLUTION def main(): n,m = read() matrix = [read() for _ in range(n)] mod = 10**11 for i in range(n-1): poss = set() for j in range(m): poss.add(matrix[i+1][j] - matrix[i][j]) if len(poss) > 2: return "NO" if len(poss) == 2 and mod != 10**11 and mod != max(poss) - min(poss): return "NO" if len(poss) == 2: mod = max(poss) - min(poss) if mod <= max(max(matrix[i]) for i in range(n)): return "NO" print("YES") print(mod) write([(matrix[i][0] - matrix[0][0]) % mod for i in range(n)]) print() write(matrix[0]) #################################################### HELPERS def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: return list(map(int, inputs.split())) def write(s="\n"): if s is None: s = "" if isinstance(s, list): s = " ".join(map(str, s)) s = str(s) print(s, end="") write(main()) ```
output
1
7,936
12
15,873
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n × m matrix v using the following formula: <image> Vasya wrote down matrix v on a piece of paper and put it in the table. A year later Vasya was cleaning his table when he found a piece of paper containing an n × m matrix w. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix v from those days. Your task is to find out if the matrix w that you've found could have been obtained by following these rules and if it could, then for what numbers k, a1, a2, ..., an, b1, b2, ..., bm it is possible. Input The first line contains integers n and m (1 ≤ n, m ≤ 100), separated by a space — the number of rows and columns in the found matrix, respectively. The i-th of the following lines contains numbers wi, 1, wi, 2, ..., wi, m (0 ≤ wi, j ≤ 109), separated by spaces — the elements of the i-th row of matrix w. Output If the matrix w could not have been obtained in the manner described above, print "NO" (without quotes) in the single line of output. Otherwise, print four lines. In the first line print "YES" (without quotes). In the second line print an integer k (1 ≤ k ≤ 1018). Note that each element of table w should be in range between 0 and k - 1 inclusively. In the third line print n integers a1, a2, ..., an (0 ≤ ai ≤ 1018), separated by spaces. In the fourth line print m integers b1, b2, ..., bm (0 ≤ bi ≤ 1018), separated by spaces. Examples Input 2 3 1 2 3 2 3 4 Output YES 1000000007 0 1 1 2 3 Input 2 2 1 2 2 0 Output YES 3 0 1 1 2 Input 2 2 1 2 2 1 Output NO Note By <image> we denote the remainder of integer division of b by c. It is guaranteed that if there exists some set of numbers k, a1, ..., an, b1, ..., bm, that you could use to make matrix w, then there also exists a set of numbers that meets the limits 1 ≤ k ≤ 1018, 1 ≤ ai ≤ 1018, 1 ≤ bi ≤ 1018 in the output format. In other words, these upper bounds are introduced only for checking convenience purposes.
instruction
0
7,937
12
15,874
Tags: constructive algorithms, math Correct Solution: ``` import sys f = sys.stdin #f = open('H:\\Portable Python 3.2.5.1\\test_248B1.txt') #r, g, b = map(int, f.readline().strip().split()) n, m = map(int, f.readline().strip().split()) v = [] max_v = 0 for i in range(n): a = [int(u) for u in f.readline().strip().split()] v.append(a) max_v = max(max_v, max(a)) #print(v) #print(max_v) #if n==1 or m==1: # print('YES') # print(max_v+1) # if n==1: # print(0) # p = [str(u) for u in v[0]] # print( ' '.join(p) ) # else: # p = [str(u[0]) for u in v] # print( ' '.join(p) )1 12 # print(0) # exit() a = [0]*n b = [0]*m a[0] = v[0][0] b[0] = 0 k = [] err = False for i in range(n-1): w = [0]*m for j in range(m): w[j] = v[i+1][j] - v[i][j] t = max(w) for j in range(m): if w[j] - t != 0 : if len(k)>0: if k[0]!=w[j] - t: err = True else: k.append(w[j] - t) a[i+1] = a[i] + t #print('a') #print(w) #print(a) for j in range(m-1): w = [0]*n for i in range(n): w[i] = v[i][j+1] - v[i][j] t = max(w) for s in range(n): if w[s] - t != 0 : if len(k)>0: if k[0]!=w[s] - t: err = True else: k.append(w[s] - t) b[j+1] = b[j] + t #print('b') #print(w) #print(b) # #print(k) if len(k)==0: k = max_v + 1 else : k = -k[0] if k<=0: err = True if err or k<=max_v: print('NO') else: if min(a)<0: a = [u+k for u in a] if min(b)<0: b = [u+k for u in b] print('YES') print(k) p = [str(u) for u in a] print( ' '.join(p) ) p = [str(u) for u in b] print( ' '.join(p) ) ```
output
1
7,937
12
15,875
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide. Output Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment. Examples Input 4 1 8 2 3 4 7 5 6 Output 3 0 1 0 Input 3 3 4 1 5 2 6 Output 0 1 1
instruction
0
7,993
12
15,986
Tags: data structures, sortings Correct Solution: ``` #!/usr/bin/env python3 from __future__ import division, print_function def least_significant_bit(i): return ((i) & -(i)) class FenwickTree(): def __init__(self, n): # 1-indexed self.n = n + 1 self.data = [0,] * self.n def add(self, index, value): # 1-indexed i = index + 1 while i < self.n: self.data[i] += value i += least_significant_bit(i) def prefix_sum(self, index): # 1-indexed i = index + 1 result = 0 while i > 0: result += self.data[i] i -= least_significant_bit(i) return result def range_sum(self, start, end): return self.prefix_sum(end) - self.prefix_sum(start-1) def main(): import sys data = iter(map(int, sys.stdin.buffer.read().decode('ascii').split())) # ~ data = iter(map(int, sys.stdin.buffer.read().split())) n = next(data) left = [0,] * n right = [0,] * n for i in range(n): a, b = next(data), next(data) left[i] = a right[i] = b order = list(range(n)) order.sort(key=lambda x: left[x]) for i, k in enumerate(order): left[k] = i order = list(range(n)) order.sort(key=lambda x:right[x]) res = [0, ] * n ft = FenwickTree(n) for i, k in enumerate(order): a = left[k] res[k] = i - ft.prefix_sum(a-1) ft.add(a, 1) sys.stdout.buffer.write('\n'.join('%d' % x for x in res).encode('ascii')) # ~ sys.stdout.buffer.write(b'\n'.join(b'%d' % x for x in res)) return 0 if __name__ == '__main__': main() ```
output
1
7,993
12
15,987
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide. Output Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment. Examples Input 4 1 8 2 3 4 7 5 6 Output 3 0 1 0 Input 3 3 4 1 5 2 6 Output 0 1 1
instruction
0
7,994
12
15,988
Tags: data structures, sortings Correct Solution: ``` #!/usr/bin/env python3 from __future__ import division, print_function def least_significant_bit(i): return ((i) & -(i)) class FenwickTree(): def __init__(self, n): # 1-indexed self.n = n + 1 self.data = [0,] * self.n def add(self, index, value): # 1-indexed i = index + 1 while i < self.n: self.data[i] += value i += least_significant_bit(i) def prefix_sum(self, index): # 1-indexed i = index + 1 result = 0 while i > 0: result += self.data[i] i -= least_significant_bit(i) return result def range_sum(self, start, end): return self.prefix_sum(end) - self.prefix_sum(start-1) def main(): import sys data = iter(map(int, sys.stdin.buffer.read().decode('ascii').split())) n = next(data) left = [0,] * n right = [0,] * n for i in range(n): a, b = next(data), next(data) left[i] = a right[i] = b order = list(range(n)) order.sort(key=lambda x: left[x]) for i, k in enumerate(order): left[k] = i order = list(range(n)) order.sort(key=lambda x:right[x]) res = [0, ] * n ft = FenwickTree(n) for i, k in enumerate(order): a = left[k] res[k] = i - ft.prefix_sum(a-1) ft.add(a, 1) sys.stdout.buffer.write('\n'.join(str(x) for x in res).encode('ascii')) return 0 if __name__ == '__main__': main() ```
output
1
7,994
12
15,989
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide. Output Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment. Examples Input 4 1 8 2 3 4 7 5 6 Output 3 0 1 0 Input 3 3 4 1 5 2 6 Output 0 1 1
instruction
0
7,995
12
15,990
Tags: data structures, sortings Correct Solution: ``` #!/usr/bin/env python3 from __future__ import division, print_function def least_significant_bit(i): return ((i) & -(i)) class FenwickTree(): def __init__(self, n): # 1-indexed self.n = n + 1 self.data = [0,] * self.n def add(self, index, value): # 1-indexed i = index + 1 while i < self.n: self.data[i] += value i += least_significant_bit(i) def prefix_sum(self, index): # 1-indexed i = index + 1 result = 0 while i > 0: result += self.data[i] i -= least_significant_bit(i) return result def range_sum(self, start, end): return self.prefix_sum(end) - self.prefix_sum(start-1) def main(): import sys data = list(map(int, sys.stdin.buffer.read().decode('ascii').split())) data.reverse() n = data.pop() left = [0,] * n right = [0,] * n for i in range(n): a, b = data.pop(), data.pop() left[i] = a right[i] = b order = list(range(n)) order.sort(key=lambda x: left[x]) for i, k in enumerate(order): left[k] = i order = list(range(n)) order.sort(key=lambda x:right[x]) res = [0, ] * n ft = FenwickTree(n) for i, k in enumerate(order): a = left[k] res[k] = i - ft.prefix_sum(a-1) ft.add(a, 1) sys.stdout.buffer.write('\n'.join(str(x) for x in res).encode('ascii')) return 0 if __name__ == '__main__': main() ```
output
1
7,995
12
15,991
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide. Output Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment. Examples Input 4 1 8 2 3 4 7 5 6 Output 3 0 1 0 Input 3 3 4 1 5 2 6 Output 0 1 1
instruction
0
7,996
12
15,992
Tags: data structures, sortings Correct Solution: ``` #!/usr/bin/env python3 from __future__ import division, print_function def least_significant_bit(i): return ((i) & -(i)) class FenwickTree(): def __init__(self, n): # 1-indexed self.n = n + 1 self.data = [0,] * self.n def add(self, index, value): # 1-indexed i = index + 1 while i < self.n: self.data[i] += value i += least_significant_bit(i) def prefix_sum(self, index): # 1-indexed i = index + 1 result = 0 while i > 0: result += self.data[i] i -= least_significant_bit(i) return result def range_sum(self, start, end): return self.prefix_sum(end) - self.prefix_sum(start-1) def main(): import sys data = iter(map(int, sys.stdin.buffer.read().decode('ascii').split())) n = next(data) left = [0,] * n right = [0,] * n for i in range(n): a, b = next(data), next(data) left[i] = a right[i] = b order = list(range(n)) order.sort(key=lambda x: left[x]) for i, k in enumerate(order): left[k] = i order = list(range(n)) order.sort(key=lambda x:right[x]) res = [0, ] * n ft = FenwickTree(n) for i, k in enumerate(order): a = left[k] res[k] = i - ft.prefix_sum(a-1) ft.add(a, 1) print('\n'.join(str(x) for x in res)) return 0 if __name__ == '__main__': main() ```
output
1
7,996
12
15,993
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide. Output Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment. Examples Input 4 1 8 2 3 4 7 5 6 Output 3 0 1 0 Input 3 3 4 1 5 2 6 Output 0 1 1
instruction
0
7,997
12
15,994
Tags: data structures, sortings Correct Solution: ``` #!/usr/bin/env python3 from __future__ import division, print_function import collections def least_significant_bit(i): return ((i) & -(i)) class FenwickTree(): def __init__(self, n): # 1-indexed self.n = n + 1 self.data = [0,] * self.n def add(self, index, value): # 1-indexed i = index + 1 while i < self.n: self.data[i] += value i += least_significant_bit(i) def prefix_sum(self, index): # 1-indexed i = index + 1 result = 0 while i > 0: result += self.data[i] i -= least_significant_bit(i) return result def range_sum(self, start, end): return self.prefix_sum(end) - self.prefix_sum(start-1) def main(): import sys data = collections.deque(map(int, sys.stdin.buffer.read().decode('ascii').split())) n = data.popleft() left = [0,] * n right = [0,] * n for i in range(n): a, b = data.popleft(), data.popleft() left[i] = a right[i] = b order = list(range(n)) order.sort(key=lambda x: left[x]) for i, k in enumerate(order): left[k] = i order = list(range(n)) order.sort(key=lambda x:right[x]) res = [0, ] * n ft = FenwickTree(n) for i, k in enumerate(order): a = left[k] res[k] = i - ft.prefix_sum(a-1) ft.add(a, 1) sys.stdout.buffer.write('\n'.join(str(x) for x in res).encode('ascii')) return 0 if __name__ == '__main__': main() ```
output
1
7,997
12
15,995
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide. Output Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment. Examples Input 4 1 8 2 3 4 7 5 6 Output 3 0 1 0 Input 3 3 4 1 5 2 6 Output 0 1 1
instruction
0
7,998
12
15,996
Tags: data structures, sortings Correct Solution: ``` from bisect import bisect_right from collections import defaultdict import os import sys from io import BytesIO, IOBase from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def sum(BIT, i): s = 0 while i > 0: s += BIT[i] i -= i & (-i) return s def update(BIT, i, v): while i < len(BIT): BIT[i] += v i += i & (-i) def find(fen, k): curr = 0 ans = 0 prevsum = 0 for i in range(19, -1, -1): if ((curr + (1 << i) < n) and fen[curr + (1 << i)] + prevsum < k): ans = curr + (1 << i) curr = ans prevsum += fen[curr] return ans + 1 def Rank(x,BIT) : return sum(BIT,x) def sum(BIT, i): s = 0 while i > 0: s += BIT[i] i -= i & (-i) return s def update(BIT, i, v): while i < len(BIT): BIT[i] += v i += i & (-i) def find(fen, k): curr = 0 ans = 0 prevsum = 0 for i in range(19, -1, -1): if ((curr + (1 << i) < n) and fen[curr + (1 << i)] + prevsum < k): ans = curr + (1 << i) curr = ans prevsum += fen[curr] return ans + 1 def Rank(x,BIT) : return sum(BIT,x) n=int(input()) inc=[] out=[] for j in range(n): p,q=map(int,input().split()) inc.append([p,j]) out.append([q,j]) inc.sort() out.sort() curr=0 j1=0 j2=0 ind=[] while(j1<n or j2<n): if j1<n and j2<n: if inc[j1][0]<=out[j2][0]: ind.append(inc[j1][1]) j1+=1 else: ind.append(out[j2][1]) j2+=1 elif j1<n: ind.append(inc[j1][1]) j1+=1 else: ind.append(out[j2][1]) j2 += 1 d=dict() j=0 res=[0]*(n) BIT = [0] * (2*n + 1) curr=0 while(j<2*n): if ind[j] not in d.keys(): d[ind[j]]=j+1 else: res[ind[j]]=curr-Rank(d[ind[j]],BIT) update(BIT,d[ind[j]],1) curr+=1 j+=1 for j in res: print(j) ```
output
1
7,998
12
15,997
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide. Output Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment. Examples Input 4 1 8 2 3 4 7 5 6 Output 3 0 1 0 Input 3 3 4 1 5 2 6 Output 0 1 1
instruction
0
7,999
12
15,998
Tags: data structures, sortings Correct Solution: ``` #!/usr/bin/env python3 from __future__ import division, print_function def least_significant_bit(i): return ((i) & -(i)) class FenwickTree(): def __init__(self, n): # 1-indexed self.n = n + 1 self.data = [0,] * self.n def add(self, index, value): # 1-indexed i = index + 1 while i < self.n: self.data[i] += value i += least_significant_bit(i) def prefix_sum(self, index): # 1-indexed i = index + 1 result = 0 while i > 0: result += self.data[i] i -= least_significant_bit(i) return result def range_sum(self, start, end): return self.prefix_sum(end) - self.prefix_sum(start-1) def main(): import sys data = iter(map(int, sys.stdin.buffer.read().split())) n = next(data) left = [0,] * n right = [0,] * n for i in range(n): a, b = next(data), next(data) left[i] = a right[i] = b order = list(range(n)) order.sort(key=lambda x: left[x]) for i, k in enumerate(order): left[k] = i order = list(range(n)) order.sort(key=lambda x:right[x]) res = [0, ] * n ft = FenwickTree(n) for i, k in enumerate(order): a = left[k] res[k] = i - ft.prefix_sum(a-1) ft.add(a, 1) sys.stdout.buffer.write('\n'.join(str(x) for x in res).encode('ascii')) return 0 if __name__ == '__main__': main() ```
output
1
7,999
12
15,999
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line. Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide. Output Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment. Examples Input 4 1 8 2 3 4 7 5 6 Output 3 0 1 0 Input 3 3 4 1 5 2 6 Output 0 1 1
instruction
0
8,000
12
16,000
Tags: data structures, sortings Correct Solution: ``` #!/usr/bin/env python3 from __future__ import division, print_function import collections def least_significant_bit(i): return ((i) & -(i)) class FenwickTree(): def __init__(self, n): # 1-indexed self.n = n + 1 self.data = [0,] * self.n def add(self, index, value): # 1-indexed i = index + 1 while i < self.n: self.data[i] += value i += least_significant_bit(i) def prefix_sum(self, index): # 1-indexed i = index + 1 result = 0 while i > 0: result += self.data[i] i -= least_significant_bit(i) return result def range_sum(self, start, end): return self.prefix_sum(end) - self.prefix_sum(start-1) def main(): import sys data = iter(map(int, sys.stdin.buffer.read().decode('ascii').split())) n = next(data) left = [0,] * n right = [0,] * n for i in range(n): a, b = next(data), next(data) left[i] = a right[i] = b order = list(range(n)) order.sort(key=lambda x: left[x]) for i, k in enumerate(order): left[k] = i order = list(range(n)) order.sort(key=lambda x:right[x]) res = [0, ] * n ft = FenwickTree(n) for i, k in enumerate(order): a = left[k] res[k] = i - ft.prefix_sum(a-1) ft.add(a, 1) sys.stdout.buffer.write('\n'.join(str(x) for x in res).encode('ascii')) return 0 if __name__ == '__main__': main() ```
output
1
8,000
12
16,001
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi with 2·xi. 2. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. Input The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct. Output Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. Examples Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1
instruction
0
8,039
12
16,078
Tags: binary search, data structures, dfs and similar, greedy, strings, trees Correct Solution: ``` from collections import defaultdict import heapq pow=[1] for i in range(30): pow.append(pow[-1]*2) n=int(input()) b=list(map(int,input().split())) d=defaultdict(lambda:0) for j in b: d[j]=1 for j in range(n): b[j]=-b[j] heapq.heapify(b) ans=[] f=1 while(f): j= -heapq.heappop(b) can=0 for i in range(31): curr=(j-(j%pow[i]))//pow[i] if curr<1: break if d[curr]==0: heapq.heappush(b,-curr) d[curr]=1 can=1 break if not can: heapq.heappush(b,-j) break for j in range(n): b[j]=-b[j] print(*b) ```
output
1
8,039
12
16,079
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi with 2·xi. 2. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. Input The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct. Output Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. Examples Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1
instruction
0
8,040
12
16,080
Tags: binary search, data structures, dfs and similar, greedy, strings, trees Correct Solution: ``` def main(): from heapq import heapify, heapreplace input() s = set(map(int, input().split())) xx = [-x for x in s] heapify(xx) while True: x = -xx[0] while x != 1: x //= 2 if x not in s: s.add(x) heapreplace(xx, -x) break else: break print(' '.join(str(-x) for x in xx)) if __name__ == '__main__': main() ```
output
1
8,040
12
16,081
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi with 2·xi. 2. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. Input The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct. Output Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. Examples Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1
instruction
0
8,041
12
16,082
Tags: binary search, data structures, dfs and similar, greedy, strings, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## from collections import Counter,defaultdict import math #for _ in range(int(input())): #n=int(input()) def matching(s): le = len(s) pi=[0]*le for i in range(1,le): j=pi[i-1] while j>0 and s[i]!=s[j]: j=pi[j-1] if(s[i]==s[j]): j+=1 pi[i]=j #return pi ## to return list of values w=set() i=le-1 while pi[i]!=0: w.add(le-pi[i]) i=pi[i]-1 return w #n,m=map(int,input().split()) #p=input() from heapq import heapify, heapreplace, heappop,heappush input() #arr=list(map(int, input().split())) #a1=list(map(int, input().split())) s = set(map(int, input().split())) xx = [-x for x in s] heapify(xx) while True: x = -xx[0] #print(x) while x != 1: x //= 2 if x not in s: s.add(x) heappop(xx) heappush(xx,-x) #heapreplace(xx, -x) break else: break print(' '.join(str(-x) for x in xx)) ```
output
1
8,041
12
16,083
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi with 2·xi. 2. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. Input The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct. Output Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. Examples Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1
instruction
0
8,042
12
16,084
Tags: binary search, data structures, dfs and similar, greedy, strings, trees Correct Solution: ``` def solve(): from heapq import merge input() # read n a = set(int(x) for x in input().split(' ')) maxe = max(a) nodemap = {} class node: __slots__ = ('left', 'right') def __init__(self): self.right = self.left = None for x in a: while (x > 0) and not (x in nodemap): nodemap[x] = node() #print(f"node({x}) created") x //= 2 for x in nodemap.keys(): y = x // 2 if x > 1: if x%2 == 1: nodemap[y].right = nodemap[x] #print(f"{y} --right--> {x}") else: nodemap[y].left = nodemap[x] #print(f"{y} --left--> {x}") root = nodemap[1] #print(list(nodemap.keys())) def f(x, root): if not root: return (-1, []) #print(f"f({x}) called") lmax, larr = f(2*x, root.left) #print(f"left({x}) = {larr}") rmax, rarr = f(2*x+1, root.right) #print(f"right({x}) = {rarr}") if x in a: return (max(lmax, x, rmax), list(merge(larr, [x], rarr))) if lmax > rmax: larr.pop() newmax = larr[-1] if len(larr) else -1 return (max(newmax, x, rmax), list(merge(larr, [x], rarr))) elif lmax < rmax: rarr.pop() newmax = rarr[-1] if len(rarr) else -1 return (max(lmax, x, newmax), list(merge(larr, [x], rarr))) else: return (-1, []) #print("running...") print(" ".join(str(x) for x in f(1, root)[1])) if __name__ == "__main__": solve() ```
output
1
8,042
12
16,085
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi with 2·xi. 2. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. Input The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct. Output Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. Examples Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1 Submitted Solution: ``` n = int(input()) p = list(map(int, input().split())) l = list(map(lambda x: (x//2, 1-x%2), p)) l.sort() v = max(p) vv = [] while True: d = [] for x, y in l: if x == 0 or x in d or x in vv: d.append(2*x+1-y) else: d.append(x) vn = max(d) if vn >= v: break v = vn vv = [] while v: vv.append(v) v //= 2 print(" ".join(map(str, d))) ```
instruction
0
8,043
12
16,086
No
output
1
8,043
12
16,087
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi with 2·xi. 2. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. Input The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct. Output Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. Examples Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1 Submitted Solution: ``` n = int(input()) y = sorted(map(int, input().split())) ans = set([1]) for num in y[1:]: tmp = num // 2 while tmp not in ans: num //= 2 tmp //= 2 ans.add(num) for num in ans: print(num, end=" ") ```
instruction
0
8,044
12
16,088
No
output
1
8,044
12
16,089
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi with 2·xi. 2. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. Input The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct. Output Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. Examples Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1 Submitted Solution: ``` input() inp=input().split() inp2=[] for i in range(len(inp)): inp[i]=int(inp[i]) inp2.append(inp[i]) inp.sort(reverse=True) for i in inp: a=i while(a>1): if(a%2==0): a=a/2 else: a=(a-1)/2 if a not in inp2: ind=inp2.index(i) del inp2[ind] inp2.append(a) i=a for i in inp2: print(i,end=' ') ```
instruction
0
8,045
12
16,090
No
output
1
8,045
12
16,091
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a set Y of n distinct positive integers y1, y2, ..., yn. Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: 1. Take any integer xi and multiply it by two, i.e. replace xi with 2·xi. 2. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. Input The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct. Output Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. Examples Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1 Submitted Solution: ``` from collections import Counter n = int(input()) y = sorted(map(int, input().split())) counts = Counter(y) for i in range(n-1, 0, -1): tmp = y[i] // 2 while counts.get(tmp, 0) > 0: tmp //= 2 if tmp != 0: tmp = y[i] while counts.get(tmp, 0) > 0: counts[tmp] -= 1 tmp //= 2 counts[tmp] += 1 for key, val in counts.items(): for i in range(val): print(key, end=" ") ```
instruction
0
8,046
12
16,092
No
output
1
8,046
12
16,093
Provide a correct Python 3 solution for this coding contest problem. You are given a permutation p = (p_1, \ldots, p_N) of \\{ 1, \ldots, N \\}. You can perform the following two kinds of operations repeatedly in any order: * Pay a cost A. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the left by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_{l + 1}, p_{l + 2}, \ldots, p_r, p_l, respectively. * Pay a cost B. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the right by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_r, p_l, \ldots, p_{r - 2}, p_{r - 1}, respectively. Find the minimum total cost required to sort p in ascending order. Constraints * All values in input are integers. * 1 \leq N \leq 5000 * 1 \leq A, B \leq 10^9 * (p_1 \ldots, p_N) is a permutation of \\{ 1, \ldots, N \\}. Input Input is given from Standard Input in the following format: N A B p_1 \cdots p_N Output Print the minimum total cost required to sort p in ascending order. Examples Input 3 20 30 3 1 2 Output 20 Input 4 20 30 4 2 3 1 Output 50 Input 1 10 10 1 Output 0 Input 4 1000000000 1000000000 4 3 2 1 Output 3000000000 Input 9 40 50 5 3 4 7 6 1 2 9 8 Output 220
instruction
0
8,232
12
16,464
"Correct Solution: ``` import sys readline = sys.stdin.readline N, A, B = map(int, readline().split()) *P, = map(int, readline().split()) Q = [0]*N for i, p in enumerate(P): Q[p-1] = i INF = 10**18 dp = [[INF]*(N+1) for i in range(N+1)] dp[0][0] = 0 for i in range(N): qi = Q[i] for j in range(N): v = dp[i][j] dp[i+1][j] = min(dp[i+1][j], v + (A if qi < j else B)) dp[i][j+1] = min(dp[i][j+1], v) if Q[i] == j: dp[i+1][j+1] = min(dp[i+1][j+1], v) for i in range(N): dp[i+1][N] = min(dp[i+1][N], dp[i][N] + A) for j in range(N): dp[N][j+1] = min(dp[N][j+1], dp[N][j]) sys.stdout.write("%d\n" % dp[N][N]) ```
output
1
8,232
12
16,465
Provide a correct Python 3 solution for this coding contest problem. You are given a permutation p = (p_1, \ldots, p_N) of \\{ 1, \ldots, N \\}. You can perform the following two kinds of operations repeatedly in any order: * Pay a cost A. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the left by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_{l + 1}, p_{l + 2}, \ldots, p_r, p_l, respectively. * Pay a cost B. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the right by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_r, p_l, \ldots, p_{r - 2}, p_{r - 1}, respectively. Find the minimum total cost required to sort p in ascending order. Constraints * All values in input are integers. * 1 \leq N \leq 5000 * 1 \leq A, B \leq 10^9 * (p_1 \ldots, p_N) is a permutation of \\{ 1, \ldots, N \\}. Input Input is given from Standard Input in the following format: N A B p_1 \cdots p_N Output Print the minimum total cost required to sort p in ascending order. Examples Input 3 20 30 3 1 2 Output 20 Input 4 20 30 4 2 3 1 Output 50 Input 1 10 10 1 Output 0 Input 4 1000000000 1000000000 4 3 2 1 Output 3000000000 Input 9 40 50 5 3 4 7 6 1 2 9 8 Output 220
instruction
0
8,233
12
16,466
"Correct Solution: ``` n, a, b = map(int, input().split()) dp = [2 ** 60] * (n + 1) dp[0] = 0 p = list(map(int, input().split())) for i in range(n): dp[i + 1] = dp[0] dp[0] += a for j in range(i): if p[j] < p[i]: dp[i + 1] = min(dp[i + 1], dp[j + 1]) dp[j + 1] += a else: dp[j + 1] += b print(min(dp)) ```
output
1
8,233
12
16,467
Provide a correct Python 3 solution for this coding contest problem. You are given a permutation p = (p_1, \ldots, p_N) of \\{ 1, \ldots, N \\}. You can perform the following two kinds of operations repeatedly in any order: * Pay a cost A. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the left by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_{l + 1}, p_{l + 2}, \ldots, p_r, p_l, respectively. * Pay a cost B. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the right by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_r, p_l, \ldots, p_{r - 2}, p_{r - 1}, respectively. Find the minimum total cost required to sort p in ascending order. Constraints * All values in input are integers. * 1 \leq N \leq 5000 * 1 \leq A, B \leq 10^9 * (p_1 \ldots, p_N) is a permutation of \\{ 1, \ldots, N \\}. Input Input is given from Standard Input in the following format: N A B p_1 \cdots p_N Output Print the minimum total cost required to sort p in ascending order. Examples Input 3 20 30 3 1 2 Output 20 Input 4 20 30 4 2 3 1 Output 50 Input 1 10 10 1 Output 0 Input 4 1000000000 1000000000 4 3 2 1 Output 3000000000 Input 9 40 50 5 3 4 7 6 1 2 9 8 Output 220
instruction
0
8,234
12
16,468
"Correct Solution: ``` N, A, B = map(int, input().split()) P = [int(a) - 1 for a in input().split()] X = [0] * N for i in range(N): pre = X X = [0] * N mi = pre[0] for j in range(N): mi = min(mi, pre[j]) X[j] = mi + (A if j < P[i] else B if j > P[i] else 0) print(min(X)) ```
output
1
8,234
12
16,469