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 is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]:
* [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list);
* [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences.
Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if:
* it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k;
* and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example:
* [10, 20, 20] lexicographically less than [10, 21, 1],
* [7, 99, 99] is lexicographically less than [10, 21, 1],
* [10, 21, 0] is lexicographically less than [10, 21, 1].
You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.
For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a.
The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).
The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests.
The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests.
Output
Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.
Examples
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
Note
In the first example, for a=[10,20,10] the optimal subsequences are:
* for k=1: [20],
* for k=2: [10,20],
* for k=3: [10,20,10].
Submitted Solution:
```
n = int(input())
c = list(map(lambda x: (int(x[1]),x[0]),enumerate(input().split())))
so = sorted(c)
for i in range(int(input())):
k,r = map(int,input().split())
now = so[-k:]
now.sort(key = lambda x: x[1])
print(now[r-1][0])
``` | instruction | 0 | 39,733 | 12 | 79,466 |
No | output | 1 | 39,733 | 12 | 79,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]:
* [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list);
* [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences.
Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if:
* it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k;
* and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example:
* [10, 20, 20] lexicographically less than [10, 21, 1],
* [7, 99, 99] is lexicographically less than [10, 21, 1],
* [10, 21, 0] is lexicographically less than [10, 21, 1].
You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.
For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a.
The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).
The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests.
The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests.
Output
Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.
Examples
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
Note
In the first example, for a=[10,20,10] the optimal subsequences are:
* for k=1: [20],
* for k=2: [10,20],
* for k=3: [10,20,10].
Submitted Solution:
```
66+965
56356
63456354
6464764
``` | instruction | 0 | 39,734 | 12 | 79,468 |
No | output | 1 | 39,734 | 12 | 79,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]:
* [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list);
* [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences.
Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if:
* it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k;
* and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example:
* [10, 20, 20] lexicographically less than [10, 21, 1],
* [7, 99, 99] is lexicographically less than [10, 21, 1],
* [10, 21, 0] is lexicographically less than [10, 21, 1].
You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.
For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the length of the sequence a.
The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).
The third line contains an integer m (1 ≤ m ≤ 100) — the number of requests.
The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests.
Output
Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.
Examples
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
Note
In the first example, for a=[10,20,10] the optimal subsequences are:
* for k=1: [20],
* for k=2: [10,20],
* for k=3: [10,20,10].
Submitted Solution:
```
n = int(input())
b = list(map(int, input().split()))
a = []
for i in range(n):
a.append([b[i], i])
a.sort()
a.reverse()
p = []
t = []
for i in range(n):
t.append(a[i])
d = t.copy()
d.sort(key=lambda x: x[1])
d.reverse()
p.append(d)
m = int(input())
#print(p)
for i in range(m):
k, pos = map(int, input().split())
d = p[k - 1].copy()
#print(d)
print(d[pos - 1][0])
``` | instruction | 0 | 39,735 | 12 | 79,470 |
No | output | 1 | 39,735 | 12 | 79,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 | 39,754 | 12 | 79,508 |
Tags: binary search, data structures, dp, greedy, sortings, two pointers
Correct Solution:
```
import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
i = 0
b = [None]*n
a = list(mints())
for v in a:
b[i] = (v, i)
i += 1
b.sort()
i = 0
c1 = [0]*n # how many moves to sort all after i with same value + all below
p = [0]*n
prev = None
ans = int(1e9)
while i < n:
j = i + 1
v = b[i][0]
while j < n and b[j][0] == v:
j += 1
if prev is None:
for z in range(i, j):
c1[z] = j - z - 1
for z in range(i, 1):
ans = min(ans, z - i + n - j)
else:
s, e = prev
k = s
while k < e and b[k][1] < b[i][1]:
k += 1
for z in range(i, j - 1):
c1[z] = j - z - 1 + e
for z in range(j - 1, j):
if k == e:
c1[z] = c1[e - 1]
else:
c1[z] = s + e - k
for z in range(i, j):
while k < e and b[k][1] < b[z][1]:
k += 1
if k == s:
ans = min(ans, z - i + e + n - j)
else:
ans = min(ans, z - i + c1[k - 1] + n - j)
prev = (i, j)
i = j
print(ans)
for i in range(mint()):
solve()
``` | output | 1 | 39,754 | 12 | 79,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 | 39,755 | 12 | 79,510 |
Tags: binary search, data structures, dp, greedy, sortings, two pointers
Correct Solution:
```
import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
b = [None]*n
i = 0
for v in mints():
b[i] = (v, i)
i += 1
b.sort()
c = [0]*n # how many moves to sort all after i with same value + all below
ans = int(1e9)
s = None
i = 0
while i < n:
j = i + 1
v = b[i][0]
while j < n and b[j][0] == v:
j += 1
if s is None:
for z in range(i, j):
c[z] = j - z - 1
ans = n - j
else:
k = s
while k < e and b[k][1] < b[i][1]:
k += 1
for z in range(i, j - 1):
c[z] = j - z - 1 + e
if k == e:
c[j - 1] = c[e - 1]
else:
c[j - 1] = s + e - k
v = n - i - j
for z in range(i, j):
while k < e and b[k][1] < b[z][1]:
k += 1
ans = min(ans, z + (e if k == s else c[k - 1]) + v)
s, e, i = i, j, j
print(ans)
for i in range(mint()):
solve()
``` | output | 1 | 39,755 | 12 | 79,511 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 | 39,756 | 12 | 79,512 |
Tags: binary search, data structures, dp, greedy, sortings, two pointers
Correct 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():
def comprs(a):
d={}
b=[x for x in a]
b.sort()
pvr,i=-1,0
for x in b:
if pvr==x:
continue
pvr=x
d[x]=i
i+=1
a=[d[x] for x in a]
return i,a
for _ in range(int(input())):
n=int(input())
a = [int(x) for x in input().split()]
m,a=comprs(a)
ans=0
idx=[[] for _ in range(m)]
for i,x in enumerate(a):
idx[x].append(i)
dp=(n,0)
for p in reversed(range(m)):
cur=idx[p]
if dp[0]>cur[-1]:
dp=(cur[0],len(cur)+dp[1])
else:
for i,x in enumerate(cur):
if x>dp[0]:
ans=max(ans,dp[1]+i)
break
cnt=len(cur)+len(idx[p+1])
for x in idx[p+1]:
if x>cur[-1]:
break
cnt-=1
dp=(cur[0],cnt)
ans=max(ans,dp[1])
for p in reversed(range(m-1)):
j=0
for i,x in enumerate(idx[p]):
while j < len(idx[p+1]) and x>idx[p+1][j]:
j+=1
ans=max(ans,i+1+len(idx[p+1])-j)
print(n-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()
``` | output | 1 | 39,756 | 12 | 79,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 | 39,757 | 12 | 79,514 |
Tags: binary search, data structures, dp, greedy, sortings, two pointers
Correct Solution:
```
for _ in range(int(input())):
n,l = int(input()),list(map(int,input().split()));id = sorted(list(zip(l,list(range(n)))));val, pos = zip(*id);blok = [];cur = [pos[0]]
for i in range(1,n):
if val[i] == val[i-1]:cur.append(pos[i])
else:cur.sort();blok.append(cur);cur = [pos[i]]
cur.sort();blok.append(cur);best,i,m = 0,0,len(blok)
for j in range(m):best = max(len(blok[j]), best)
while True:
if i >= m-2:break
cyk = min(blok[i+1]);j = -1
while j+1 < len(blok[i]) and blok[i][j+1] < cyk:j += 1
su = (j+1);ii = i+2
while ii < m:
if min(blok[ii]) > max(blok[ii-1]):su += len(blok[ii-1]);ii += 1
else:break
if ii == m:su += len(blok[-1]);best = max(best, su)
else:
xxx = max(blok[ii-1]);su += len(blok[ii-1]);inde = len(blok[ii])-1
while inde >= 0 and blok[ii][inde] >= xxx:su += 1;inde -= 1
best = max(best,su)
i = max(i+1, ii-1)
for i in range(1,m):
b1 = blok[i];b0 = blok[i-1];l0,l1,i1 = len(b0),len(b1),0
for ind in range(l0):
while True:
if i1 < l1 and b1[i1] <= b0[ind]:i1 += 1
else:break
if l1 == i1:break
best = max(best, (ind+1)+(l1-i1))
print(n-best)
``` | output | 1 | 39,757 | 12 | 79,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 | 39,758 | 12 | 79,516 |
Tags: binary search, data structures, dp, greedy, sortings, two pointers
Correct Solution:
```
# f = open('test.py')
# def input():
# return f.readline().replace('\n','')
from collections import defaultdict
import bisect
# from collections import deque
def read_list():
return list(map(int,input().strip().split(' ')))
def print_list(l):
print(' '.join(map(str,l)))
N = int(input())
for _ in range(N):
n = int(input())
nums = read_list()
dic = defaultdict(list)
for i in range(n):
dic[nums[i]].append(i)
data = list(set(nums))
data.sort()
l = len(data)
res = 0
if l>1:
ind = bisect.bisect_left(dic[data[0]],dic[data[1]][0])
ln = len(dic[data[1]])
for j in range(len(dic[data[0]])-1,ind-1,-1):
res = max(res,j+1+ln-bisect.bisect_left(dic[data[1]],dic[data[0]][j]))
tmp = ind+ln
else:
tmp = 0
for i in range(2,l):
if dic[data[i]][0]>dic[data[i-1]][-1]:
tmp+=len(dic[data[i]])
else:
res = max(res,tmp+len(dic[data[i]])-bisect.bisect_left(dic[data[i]],dic[data[i-1]][-1]))
ind = bisect.bisect_left(dic[data[i-1]],dic[data[i]][0])
ln = len(dic[data[i]])
for j in range(len(dic[data[i-1]])-1,ind-1,-1):
res = max(res,j+1+ln-bisect.bisect_left(dic[data[i]],dic[data[i-1]][j]))
tmp = ind+ln
res = max(res,tmp)
for a in dic.values():
res = max(len(a),res)
print(n-res)
``` | output | 1 | 39,758 | 12 | 79,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 | 39,759 | 12 | 79,518 |
Tags: binary search, data structures, dp, greedy, sortings, two pointers
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
id = list(zip(l,list(range(n))))
id.sort()
val, pos = zip(*id)
blok = []
cur = [pos[0]]
for i in range(1,n):
if val[i] == val[i-1]:
cur.append(pos[i])
else:
cur.sort()
blok.append(cur)
cur = [pos[i]]
cur.sort()
blok.append(cur)
best = 0
m = len(blok)
for j in range(m):
best = max(len(blok[j]), best)
i = 0
while True:
if i >= m-2:
break
cyk = min(blok[i+1])
j = -1
while j+1 < len(blok[i]) and blok[i][j+1] < cyk:
j += 1
su = (j+1)
ii = i+2
while ii < m:
if min(blok[ii]) > max(blok[ii-1]):
su += len(blok[ii-1])
ii += 1
else:
break
if ii == m:
su += len(blok[-1])
best = max(best, su)
else:
xxx = max(blok[ii-1])
su += len(blok[ii-1])
inde = len(blok[ii])-1
while inde >= 0 and blok[ii][inde] >= xxx:
su += 1
inde -= 1
best = max(best,su)
i = max(i+1, ii-1)
for i in range(1,m):
b1 = blok[i];b0 = blok[i-1];l0,l1,i1 = len(b0),len(b1),0
for ind in range(l0):
while True:
if i1 < l1 and b1[i1] <= b0[ind]:i1 += 1
else:break
if l1 == i1:break
best = max(best, (ind+1)+(l1-i1))
print(n-best)
``` | output | 1 | 39,759 | 12 | 79,519 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 | 39,760 | 12 | 79,520 |
Tags: binary search, data structures, dp, greedy, sortings, 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 | 39,760 | 12 | 79,521 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 | 39,761 | 12 | 79,522 |
Tags: binary search, data structures, dp, greedy, sortings, two pointers
Correct Solution:
```
from sys import stdin, stdout
# 4 7 9 [2] [3]
# 3 4 7 9 [2]
# 2 3 4 7 9
# 4 7 9 [2 3]
# [4 7 9] 2 3
# [4] 7 9 2 3
# [7] 9 2 3 4
# [9] 2 3 4 7
# 2 3 4 7 9
# 4 [7 9] 3 3 10
# 1 2 3 0 0 4
# 1 2 3 4
# find longest subseq that already sorted
# 1
# 1 2
# 1 2 3
# 10, 9, 1, 7, 0, 8, 0, 7, 3, 6, 2, 5, 4, 5, 11, 6, 7, 12, 0, 6
# 5 5 6 6
# 2 2 3 3
# dp:
# dp[i,0]: counts of a[i], ex 3 [3]
# dp[i,1]: still has a[i], ex 2 2 [3]
# dp[i,2]: no a[i] ex 2 2 3 [3]
def flying_sort(n, a):
b = sorted(a)
dic = {}
seq = 1
dic[b[0]] = seq
num = [0 for i in range(n + 1)]
head = [0 for i in range(n + 1)]
tail = [-1 for i in range(n+1)]
pos = [0 for i in range(n+1)]
for i in range(1, len(b)):
if b[i] != b[i-1]:
seq += 1
dic[b[i]] = seq
for i in range(len(a)):
a[i] = dic[a[i]]
num[a[i]] += 1
tail[a[i]] = i+1
if head[a[i]] == 0:
head[a[i]] = i+1
# find longest subseq
dp = [[0, 0, 0] for i in range(n+1)]
maxseq = 0
#print(a)
for i in range(1, n+1):
v = a[i-1]
dp[i][0] = dp[pos[v]][0] + 1
#print(v)
dp[i][1] = max(dp[pos[v]][1] + 1, dp[pos[v - 1]][0] + 1, dp[pos[v - 1]][2] + 1)
if tail[v] == i:
dp[i][2] = dp[head[v]][1] + num[v] - 1
pos[v] = i
for k in range(3):
maxseq = max(maxseq, dp[i][k])
#for i in range(len(dp)):
# print(a[i-1])
# print(dp[i])
res = len(a) - maxseq
return res
if __name__ == '__main__':
t = int(stdin.readline())
for i in range(t):
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
stdout.write(str(flying_sort(n, a)) + '\n')
``` | output | 1 | 39,761 | 12 | 79,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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:
```
# ------------------- 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))
``` | instruction | 0 | 39,762 | 12 | 79,524 |
Yes | output | 1 | 39,762 | 12 | 79,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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:
```
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
t = int(input())
ans_a = [0] * t
for ti in range(t):
n = int(input())
a = list(map(int, input().split()))
comp_dict = {x: i for i, x in enumerate(sorted(set(a)))}
cnt = [0] * n
max_cnt = [0] * n
for i in range(n):
a[i] = comp_dict[a[i]]
max_cnt[a[i]] += 1
dp = [[0] * 3 for _ in range(n + 1)]
for cur in a:
# j=2 -> j=2
dp[cur][2] += 1
# j=1 -> j=2
if cnt[cur - 1] == max_cnt[cur - 1]:
dp[cur][2] = max(dp[cur][2], dp[cur - 1][1] + 1)
# j=0 -> j=2
dp[cur][2] = max(dp[cur][2], dp[cur - 1][0] + 1)
# j=1 -> j=1
if cnt[cur] == 0:
if cnt[cur - 1] == max_cnt[cur - 1]:
dp[cur][1] = max(dp[cur][1], dp[cur - 1][1] + 1)
else:
dp[cur][1] += 1
# j=0 -> j=1
if cnt[cur] == 0:
dp[cur][1] = max(dp[cur][1], dp[cur - 1][0] + 1)
# j=0 -> j=0
dp[cur][0] += 1
cnt[cur] += 1
ans_a[ti] = n - max(dp[i][-1] for i in range(n))
sys.stdout.buffer.write(('\n'.join(map(str, ans_a)) + '\n').encode('utf-8'))
if __name__ == '__main__':
main()
``` | instruction | 0 | 39,763 | 12 | 79,526 |
Yes | output | 1 | 39,763 | 12 | 79,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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:
```
for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
id = list(zip(l,list(range(n))))
id.sort()
val, pos = zip(*id)
blok = []
cur = [pos[0]]
for i in range(1,n):
if val[i] == val[i-1]:
cur.append(pos[i])
else:
cur.sort()
blok.append(cur)
cur = [pos[i]]
cur.sort();blok.append(cur)
best,i,m = 0,0,len(blok)
for j in range(m):best = max(len(blok[j]), best)
while True:
if i >= m-2:break
cyk = min(blok[i+1]);j = -1
while j+1 < len(blok[i]) and blok[i][j+1] < cyk:j += 1
su = (j+1);ii = i+2
while ii < m:
if min(blok[ii]) > max(blok[ii-1]):su += len(blok[ii-1]);ii += 1
else:break
if ii == m:su += len(blok[-1]);best = max(best, su)
else:
xxx = max(blok[ii-1]);su += len(blok[ii-1]);inde = len(blok[ii])-1
while inde >= 0 and blok[ii][inde] >= xxx:su += 1;inde -= 1
best = max(best,su)
i = max(i+1, ii-1)
for i in range(1,m):
b1 = blok[i];b0 = blok[i-1];l0,l1,i1 = len(b0),len(b1),0
for ind in range(l0):
while True:
if i1 < l1 and b1[i1] <= b0[ind]:i1 += 1
else:break
if l1 == i1:break
best = max(best, (ind+1)+(l1-i1))
print(n-best)
``` | instruction | 0 | 39,764 | 12 | 79,528 |
Yes | output | 1 | 39,764 | 12 | 79,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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:
```
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def main():
for _ in range(II()):
inf=10**9
n=II()
aa=LI()
s=set(aa)
enc={a:i for i,a in enumerate(sorted(s))}
aa=[enc[a] for a in aa]
#print(aa)
first = [False] * n
fin = [False] * len(s)
for i in range(n):
if fin[aa[i]]: continue
first[i] = True
fin[aa[i]] = True
#print(first)
end = [False] * n
fin = [False] * len(s)
for i in range(n - 1, -1, -1):
if fin[aa[i]]: continue
end[i] = True
fin[aa[i]] = True
#print(end)
last=[-1]*len(s)
dp=[[0]*3 for _ in range(n)]
mx=0
for i,a in enumerate(aa):
val=1
i0=last[a]
if i0!=-1:val=dp[i0][0]+1
dp[i][0]=val
mx=max(mx,val)
val = -inf
if i0 != -1: val = dp[i0][1] + 1
i1 = -1
if a: i1 = last[a - 1]
if i1 != -1:
if first[i]:val = max(val, dp[i1][0] + 1)
if end[i1] and first[i]: val = max(val, dp[i1][1] + 1)
dp[i][1] = val
mx=max(mx,val)
val = -inf
if i0 != -1: val = dp[i0][2] + 1
if i1 != -1:
val = max(val, dp[i1][0] + 1)
if end[i1]: val = max(val, dp[i1][1] + 1)
dp[i][2] = val
mx=max(mx,val)
last[a]=i
#print(dp)
print(n-mx)
main()
``` | instruction | 0 | 39,765 | 12 | 79,530 |
Yes | output | 1 | 39,765 | 12 | 79,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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:
```
import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
a = list(mints())
b = list(enumerate(a))
b.sort(key=lambda a:a[1])
c1 = [0]*n
c2 = [0]*n
hh = [0]*n
c = 0
h = 0
p = -1
w = -1
for z in range(n):
i, v = b[z]
if i > p:
c += 1
else:
c = 1
if w != v:
zz = z
while zz < n and b[zz][1] == v:
h += 1
zz += 1
w = v
c1[i] = h-c
hh[i] = h
p = i
c = 0
h = 0
p = -1
ans = n+n
w = -1
for z in range(len(b)-1,-1,-1):
i, v = b[z]
if i < p:
c += 1
else:
c = 1
if w != v:
zz = z
while zz >= 0 and b[zz][1] == v:
h += 1
zz -= 1
w = v
c2[i] = h-c
p = i
i = 0
j = 0
k = 0
kv = -1
while i < n:
p, v = b[i]
while j < n and b[j][1] == v:
j += 1
if k < j:
k = j
if k != n:
kv = b[k][1]
while k < n and b[k][1] == kv and b[k][0] < p:
k += 1
if k == n or b[k][1] != kv:
ans = min(ans, c1[p] + n - hh[p])
else:
ans = min(ans, c1[p] + c2[b[k][0]])
i += 1
print(ans)
for i in range(mint()):
solve()
``` | instruction | 0 | 39,766 | 12 | 79,532 |
No | output | 1 | 39,766 | 12 | 79,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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:
```
for t in range(int(input())):
n = int(input())
aa = list(map(int, input().split(' ')))
asort = sorted([(v, i) for i, v in enumerate(aa)]);
inds = {}
for a, ai in asort:
if a not in inds:
inds[a] = []
inds[a] += [ai]
def left_eq(b, i):
binds = inds[b]
l = -1
r = len(binds) - 1
while l < r:
m = (l + r + 1) // 2
if binds[m] < i:
l = m
else:
r = m - 1
return l + 1
def right_eq(b, i):
binds = inds[b]
l = 0
r = len(binds)
while l < r:
m = (l + r) // 2
if binds[m] > i:
r = m
else:
l = m + 1
return len(binds) - l
ls = [None] * n
for i, (a, ai) in enumerate(asort):
if i == 0:
ls[ai] = 1
continue
if asort[i - 1][1] < ai:
curl = ls[asort[i - 1][1]] + 1
else:
curl = left_eq(asort[i - 1][0], ai) + 1
ls[ai] = curl
#print('before:', ls)
for i, (a, ai) in reversed(list(enumerate(asort))):
if i == n - 1:
continue
if asort[i + 1][0] != a:
ls[ai] += right_eq(asort[i + 1][0], ai)
#print('after:', ls)
alter = []
values = list(inds.keys())
v2vi = { v: i for i, v in enumerate(values) }
for i, (a, ai) in enumerate(asort):
avin = v2vi[a]
if avin > 0:
alter += [1] # [left_eq(values[avin-1], ai) + 1] # + right_eq(a, ai)]
maxSeqLen = max(ls) # max(max(ls), max(alter))
print(n - maxSeqLen)
``` | instruction | 0 | 39,767 | 12 | 79,534 |
No | output | 1 | 39,767 | 12 | 79,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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():
def comprs(a):
d={}
b=[x for x in a]
b.sort()
pvr,i=-1,0
for x in b:
if pvr==x:
continue
pvr=x
d[x]=i
i+=1
a=[d[x] for x in a]
return i,a
tc=int(input())
for tt in range(tc):
n=int(input())
a = [int(x) for x in input().split()]
m,a=comprs(a)
if tt+1==4999:
print(*a)
if tc==10000:
continue
ans=0
idx=[[] for _ in range(m)]
for i,x in enumerate(a):
idx[x].append(i)
dp=(n,0)
# print(a)
for p in reversed(range(m)):
cur=idx[p]
if dp[0]>cur[-1]:
dp=(cur[0],len(cur)+dp[1])
else:
for i,x in enumerate(cur):
if x>dp[0]:
ans=max(ans,dp[1]+i)
break
cnt=len(cur)+len(idx[p+1])
for x in idx[p+1]:
if x>cur[-1]:
break
cnt-=1
dp=(cur[0],cnt)
# print(dp,p)
ans=max(ans,dp[1])
print(n-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 | 39,768 | 12 | 79,536 |
No | output | 1 | 39,768 | 12 | 79,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). 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, 2, 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, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 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 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 ≤ 10^4) — 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 ≤ 2 ⋅ 10^5) — the size 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. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 ⋅ 10^5.
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
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] → [2, 4, 7, 2, 9] → [2, 2, 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 bisect import bisect_left, bisect_right
class Result:
def __init__(self, index, value):
self.index = index
self.value = value
class BinarySearch:
def __init__(self):
pass
@staticmethod
def greater_than(num: int, func, size: int = 1):
"""Searches for smallest element greater than num!"""
if isinstance(func, list):
index = bisect_right(func, num)
if index == len(func):
return Result(None, None)
else:
return Result(index, func[index])
else:
alpha, omega = 0, size - 1
if func(omega) <= num:
return Result(None, None)
while alpha < omega:
if func(alpha) > num:
return Result(alpha, func(alpha))
if omega == alpha + 1:
return Result(omega, func(omega))
mid = (alpha + omega) // 2
if func(mid) > num:
omega = mid
else:
alpha = mid
@staticmethod
def less_than(num: int, func, size: int = 1):
"""Searches for largest element less than num!"""
if isinstance(func, list):
index = bisect_left(func, num) - 1
if index == -1:
return Result(None, None)
else:
return Result(index, func[index])
else:
alpha, omega = 0, size - 1
if func(alpha) >= num:
return Result(None, None)
while alpha < omega:
if func(omega) < num:
return Result(omega, func(omega))
if omega == alpha + 1:
return Result(alpha, func(alpha))
mid = (alpha + omega) // 2
if func(mid) < num:
alpha = mid
else:
omega = mid
# ------------------- 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
bs = BinarySearch()
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()))
di = {}
for i in range(n):
if a[i] not in di:
di[a[i]] = []
di[a[i]] += [i]
se = sorted(list(set(a)))
ans = 0
cn = [1]*n
for i in range(len(se)-1, -1, -1):
if i == len(se) - 1:
for j in range(len(di[se[i]])):
cn[di[se[i]][j]] = len(di[se[i]]) - j
continue
cur = se[i]
for j in range(len(di[cur])-1, -1, -1):
if j != len(di[cur]) - 1:
cn[di[cur][j]] = len(di[cur]) - j + cn[di[cur][-1]] - 1
#print(di[cur][j], cn[di[cur][j]])
val = bs.greater_than(di[cur][j], di[se[i+1]]).value
val2 = bs.less_than(di[cur][j], di[se[i+1]]).value
if val is not None and val2 is None:
cn[di[cur][j]] = max(cn[di[cur][j]], cn[val] + 1)
elif val is not None:
ind = bs.greater_than(di[cur][j], di[se[i+1]]).index
cn[di[cur][j]] = max(cn[di[cur][j]], len(di[se[i]])-j + len(di[se[i+1]])-ind)
#print([(a[i], cn[i]) for i in range(n)])
#print(a)
print(n-max(cn))
``` | instruction | 0 | 39,769 | 12 | 79,538 |
No | output | 1 | 39,769 | 12 | 79,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead.
You should perform the given operation n - 1 times and make the resulting number that will be left on the board as small as possible.
For example, if n = 4, the following course of action is optimal:
1. choose a = 4 and b = 2, so the new number is 3, and the whiteboard contains [1, 3, 3];
2. choose a = 3 and b = 3, so the new number is 3, and the whiteboard contains [1, 3];
3. choose a = 1 and b = 3, so the new number is 2, and the whiteboard contains [2].
It's easy to see that after n - 1 operations, there will be left only one number. Your goal is to minimize it.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The only line of each test case contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of integers written on the board initially.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, in the first line, print the minimum possible number left on the board after n - 1 operations. Each of the next n - 1 lines should contain two integers — numbers a and b chosen and erased in each operation.
Example
Input
1
4
Output
2
2 4
3 3
3 1 | instruction | 0 | 39,804 | 12 | 79,608 |
Tags: constructive algorithms, data structures, greedy, implementation, math
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
if n==2:
print(2)
print(1,2)
else:
print(2)
print(n,n-2)
print(n-1,n-1)
a=list(range(1,n))
for i in range(len(a)-1,1,-1):
print(a[i],a[i]-2)
``` | output | 1 | 39,804 | 12 | 79,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead.
You should perform the given operation n - 1 times and make the resulting number that will be left on the board as small as possible.
For example, if n = 4, the following course of action is optimal:
1. choose a = 4 and b = 2, so the new number is 3, and the whiteboard contains [1, 3, 3];
2. choose a = 3 and b = 3, so the new number is 3, and the whiteboard contains [1, 3];
3. choose a = 1 and b = 3, so the new number is 2, and the whiteboard contains [2].
It's easy to see that after n - 1 operations, there will be left only one number. Your goal is to minimize it.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The only line of each test case contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of integers written on the board initially.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, in the first line, print the minimum possible number left on the board after n - 1 operations. Each of the next n - 1 lines should contain two integers — numbers a and b chosen and erased in each operation.
Example
Input
1
4
Output
2
2 4
3 3
3 1 | instruction | 0 | 39,805 | 12 | 79,610 |
Tags: constructive algorithms, data structures, greedy, implementation, math
Correct Solution:
```
from sys import stdin,stdout
for _ in range(int(input())):
n=int(input())
array=[i for i in range(1,n+1)]
arr=[]
x=n-1
for _ in range(n-1):
arr.append([array[x],array[x-1]])
ele=(array[x]+array[x-1]+1)//2
array.pop()
array.pop()
array.append(ele)
x-=1
print(array[0])
for k in arr:
print(*k)
``` | output | 1 | 39,805 | 12 | 79,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead.
You should perform the given operation n - 1 times and make the resulting number that will be left on the board as small as possible.
For example, if n = 4, the following course of action is optimal:
1. choose a = 4 and b = 2, so the new number is 3, and the whiteboard contains [1, 3, 3];
2. choose a = 3 and b = 3, so the new number is 3, and the whiteboard contains [1, 3];
3. choose a = 1 and b = 3, so the new number is 2, and the whiteboard contains [2].
It's easy to see that after n - 1 operations, there will be left only one number. Your goal is to minimize it.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The only line of each test case contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of integers written on the board initially.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, in the first line, print the minimum possible number left on the board after n - 1 operations. Each of the next n - 1 lines should contain two integers — numbers a and b chosen and erased in each operation.
Example
Input
1
4
Output
2
2 4
3 3
3 1 | instruction | 0 | 39,808 | 12 | 79,616 |
Tags: constructive algorithms, data structures, greedy, implementation, math
Correct Solution:
```
# your code goes here
# your code goes here
for i in range(int(input())):
a1=[]
n=int(input())
lst=[i for i in range(1,n+1)]
lst=lst[::-1]
if(n==2):
print(2)
print(1,2)
else:
x1=lst[0]+lst[1]
x=x1//2
if(x1%2!=0):
x+=1
a1.append([lst[0],lst[1]])
for i in range(2,len(lst)):
x1=x+lst[i]
a1.append([x,lst[i]])
x=x1//2
if(x1%2!=0):
x+=1
print(x)
for i in a1:
print(*i)
``` | output | 1 | 39,808 | 12 | 79,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers. Define the cost of some array t as follows:
$$$cost(t) = ∑_{x ∈ set(t) } last(x) - first(x),$$$
where set(t) is the set of all values in t without repetitions, first(x), and last(x) are the indices of the first and last occurrence of x in t, respectively. In other words, we compute the distance between the first and last occurrences for each distinct element and sum them up.
You need to split the array a into k consecutive segments such that each element of a belongs to exactly one segment and the sum of the cost of individual segments is minimum.
Input
The first line contains two integers n, k (1 ≤ n ≤ 35 000, 1 ≤ k ≤ min(n,100)).
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
Output
Output the minimum sum of the cost of individual segments.
Examples
Input
7 2
1 6 6 4 6 6 6
Output
3
Input
7 4
5 5 5 5 2 3 3
Output
1
Note
In the first example, we can divide the array into [1,6,6,4] and [6,6,6]. Cost of [1,6,6,4] will be (1-1) + (3 - 2) + (4-4) = 1 and cost of [6,6,6] will be 3-1 = 2. Total cost would be 1 + 2 = 3.
In the second example, divide the array into [5,5],[5],[5,2,3] and [3]. Total Cost would be 1 + 0 + 0 + 0 = 1.
Submitted Solution:
```
import sys
from bisect import bisect_left as bl, bisect_right as br
input = sys.stdin.readline
n, k = map(int, input().split())
a = list(map(int, input().split()))
ls = [0, n]
res = 0
for _ in range(k - 1):
nextls = []
for tt in range(len(ls) - 1):
ll = ls[tt]
rr = ls[tt + 1]
s = [[] for _ in range(n + 1)]
for i in range(ll, rr): s[a[i]].append(i)
imos = [0] * (n + 1)
for x in range(1, n + 1):
for t in range(len(s[x]) - 1):
l = s[x][t]
r = s[x][t + 1]
imos[l] -= r - l
imos[r] += r - l
mn = 0
for i in range(ll, rr):
imos[i + 1] += imos[i]
mn = min(mn, imos[i], imos[i + 1])
for i in range(n - 1, -1, -1):
if mn == imos[i]:
nextls.append((mn, max(ll + 1, i)))
#print(imos)
ls.append(min(nextls, key = lambda x: (x[0], abs(n // 2 - x[1])))[1])
ls.sort()
#print(ls)
res += min(nextls, key = lambda x: x[0])[0]
s = [[] for _ in range(n + 1)]
for i in range(n): s[a[i]].append(i)
for x in range(1, n + 1):
if s[x]:
res += s[x][-1] - s[x][0]
print(res)
``` | instruction | 0 | 39,864 | 12 | 79,728 |
No | output | 1 | 39,864 | 12 | 79,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers. Define the cost of some array t as follows:
$$$cost(t) = ∑_{x ∈ set(t) } last(x) - first(x),$$$
where set(t) is the set of all values in t without repetitions, first(x), and last(x) are the indices of the first and last occurrence of x in t, respectively. In other words, we compute the distance between the first and last occurrences for each distinct element and sum them up.
You need to split the array a into k consecutive segments such that each element of a belongs to exactly one segment and the sum of the cost of individual segments is minimum.
Input
The first line contains two integers n, k (1 ≤ n ≤ 35 000, 1 ≤ k ≤ min(n,100)).
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
Output
Output the minimum sum of the cost of individual segments.
Examples
Input
7 2
1 6 6 4 6 6 6
Output
3
Input
7 4
5 5 5 5 2 3 3
Output
1
Note
In the first example, we can divide the array into [1,6,6,4] and [6,6,6]. Cost of [1,6,6,4] will be (1-1) + (3 - 2) + (4-4) = 1 and cost of [6,6,6] will be 3-1 = 2. Total cost would be 1 + 2 = 3.
In the second example, divide the array into [5,5],[5],[5,2,3] and [3]. Total Cost would be 1 + 0 + 0 + 0 = 1.
Submitted Solution:
```
n,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(set(a))
b.sort()
c=abs(b[1]-b[0])
print(c)
``` | instruction | 0 | 39,865 | 12 | 79,730 |
No | output | 1 | 39,865 | 12 | 79,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers. Define the cost of some array t as follows:
$$$cost(t) = ∑_{x ∈ set(t) } last(x) - first(x),$$$
where set(t) is the set of all values in t without repetitions, first(x), and last(x) are the indices of the first and last occurrence of x in t, respectively. In other words, we compute the distance between the first and last occurrences for each distinct element and sum them up.
You need to split the array a into k consecutive segments such that each element of a belongs to exactly one segment and the sum of the cost of individual segments is minimum.
Input
The first line contains two integers n, k (1 ≤ n ≤ 35 000, 1 ≤ k ≤ min(n,100)).
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
Output
Output the minimum sum of the cost of individual segments.
Examples
Input
7 2
1 6 6 4 6 6 6
Output
3
Input
7 4
5 5 5 5 2 3 3
Output
1
Note
In the first example, we can divide the array into [1,6,6,4] and [6,6,6]. Cost of [1,6,6,4] will be (1-1) + (3 - 2) + (4-4) = 1 and cost of [6,6,6] will be 3-1 = 2. Total cost would be 1 + 2 = 3.
In the second example, divide the array into [5,5],[5],[5,2,3] and [3]. Total Cost would be 1 + 0 + 0 + 0 = 1.
Submitted Solution:
```
from collections import defaultdict
def list_duplicates(seq):
tally = defaultdict(list)
for i,item in enumerate(seq):
tally[item].append(i)
return ((key,locs) for key,locs in tally.items()
if len(locs)>1)
arr1=[int(item) for item in input(" ").split()]
n=arr1[0]
k=arr1[1]
arr=[int(item) for item in input(" ").split()]
count=0
midarr=[]
midarr.append(arr)
while(k!=0):
count=0
newmidarr=[]
for ar in midarr:
for dup in sorted(list_duplicates(ar)):
count+=dup[1][-1]-dup[1][0]
#print("count is", + count)
mid=int(count/2)
newmidarr.append(ar[0:mid+1])
newmidarr.append(ar[mid+1:])
k-=1
midarr=[]
#print(newmidarr)
midarr=newmidarr
print(count)
``` | instruction | 0 | 39,866 | 12 | 79,732 |
No | output | 1 | 39,866 | 12 | 79,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers. Define the cost of some array t as follows:
$$$cost(t) = ∑_{x ∈ set(t) } last(x) - first(x),$$$
where set(t) is the set of all values in t without repetitions, first(x), and last(x) are the indices of the first and last occurrence of x in t, respectively. In other words, we compute the distance between the first and last occurrences for each distinct element and sum them up.
You need to split the array a into k consecutive segments such that each element of a belongs to exactly one segment and the sum of the cost of individual segments is minimum.
Input
The first line contains two integers n, k (1 ≤ n ≤ 35 000, 1 ≤ k ≤ min(n,100)).
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
Output
Output the minimum sum of the cost of individual segments.
Examples
Input
7 2
1 6 6 4 6 6 6
Output
3
Input
7 4
5 5 5 5 2 3 3
Output
1
Note
In the first example, we can divide the array into [1,6,6,4] and [6,6,6]. Cost of [1,6,6,4] will be (1-1) + (3 - 2) + (4-4) = 1 and cost of [6,6,6] will be 3-1 = 2. Total cost would be 1 + 2 = 3.
In the second example, divide the array into [5,5],[5],[5,2,3] and [3]. Total Cost would be 1 + 0 + 0 + 0 = 1.
Submitted Solution:
```
'''t=int(input())
from math import factorial
for _ in range(t):'''
n,k=map(int,input().split())
s=0
p=0
nl=list(map(int,input().split()))
na={}
for i in range(n):
if nl[i] not in na.keys():
na[nl[i]]=1
else:
na[nl[i]]+=1
for ele in na.values():
if ele>1:
s+=ele
p+=1
print(s-k-p+1)
``` | instruction | 0 | 39,867 | 12 | 79,734 |
No | output | 1 | 39,867 | 12 | 79,735 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it. | instruction | 0 | 40,463 | 12 | 80,926 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
if __name__ == '__main__':
n = int(input())
ss = map(int, input().split())
q = int(input())
acc = 0
sacc = [0]
for s in ss:
acc += s
sacc.append(acc)
for _ in range(q):
l, r = map(int, input().split())
print((sacc[r] - sacc[l - 1])//10)
``` | output | 1 | 40,463 | 12 | 80,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it. | instruction | 0 | 40,464 | 12 | 80,928 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
n=int(input())
s=list(map(int,input().split()))
q=int(input())
pre=[0]*n
pre[0]=s[0]
for i in range(1,n):
pre[i]=pre[i-1]+s[i]
for q1 in range(q):
q2=list(map(int,input().split()))
if(q2[0]==1):
print((pre[q2[1]-1])//10)
else:
print((pre[q2[1]-1]-pre[q2[0]-2])//10)
``` | output | 1 | 40,464 | 12 | 80,929 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it. | instruction | 0 | 40,465 | 12 | 80,930 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
n=int(input())
kune=list(map(int, input().split()))
m=int(input())
subliste=[]
slatkisi=[]
zbrojkuna=[]
we=0
for i in kune:
zbrojkuna.append(we+i)
we+=i
for i in range(m):
l,r=map(int, input().split())
slatkis=0
if l!=1:
slatkis+=((zbrojkuna[r-1]-zbrojkuna[l-2])//10)
else:
slatkis+=((zbrojkuna[r-1])//10)
slatkisi.append(slatkis)
for i in slatkisi:
print(i)
``` | output | 1 | 40,465 | 12 | 80,931 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it. | instruction | 0 | 40,466 | 12 | 80,932 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
import math
from collections import Counter,defaultdict
I =lambda:int(input())
M =lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))
n=I()
a=LI()
b=[0]*(n+1);c=0
for i in range(n):
c+=a[i]
b[i+1]=c
m=I()
for i in range(m):
c,d=M()
print((b[d]-b[c-1])//10)
``` | output | 1 | 40,466 | 12 | 80,933 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it. | instruction | 0 | 40,467 | 12 | 80,934 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
n=int(input())
arr=list(map(int,input().split()))
sumarray=[0]*(n+1)
tot=0
for i in range(n):
tot+=arr[i]
sumarray[i+1]=tot
# print(arr)
# print(sumarray)
q=int(input())
for i in range(q):
l,r=list(map(int,input().split()))
l-=1
temp=sumarray[r]-sumarray[l]
print(temp//10)
``` | output | 1 | 40,467 | 12 | 80,935 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it. | instruction | 0 | 40,468 | 12 | 80,936 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
# Author Name: Ajay Meena
# Codeforce : https://codeforces.com/profile/majay1638
import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout
# -------------- INPUT FUNCTIONS ------------------
def get_ints_in_variables(): return map(
int, sys.stdin.readline().strip().split())
def get_int(): return int(sys.stdin.readline())
def get_ints_in_list(): return list(
map(int, sys.stdin.readline().strip().split()))
def get_list_of_list(n): return [list(
map(int, sys.stdin.readline().strip().split())) for _ in range(n)]
def get_string(): return sys.stdin.readline().strip()
# -------- SOME CUSTOMIZED FUNCTIONS-----------
def myceil(x, y): return (x + y - 1) // y
# -------------- SOLUTION FUNCTION ------------------
def Solution():
# Write Your Code Here
n = get_int()
arr = get_ints_in_list()
q = get_int()
perfix = [0]
for v in arr:
perfix.append(perfix[-1]+v)
# print(perfix)
for _ in range(q):
l, r = get_ints_in_variables()
print((perfix[r]-perfix[l-1])//10)
def main():
# Take input Here and Call solution function
Solution()
# calling main Function
if __name__ == '__main__':
main()
``` | output | 1 | 40,468 | 12 | 80,937 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it. | instruction | 0 | 40,469 | 12 | 80,938 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
n = int(input())
lst = list(map(int,input().split()))
cum = [0,lst[0]]
for x in range(1,n):
cum.append( cum[x] + lst[x])
q = int(input())
for x in range(0,q):
l,r = map(int,input().split())
#print(l,r)
ans = cum[r] - cum[l-1];
print((ans//10))
``` | output | 1 | 40,469 | 12 | 80,939 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it. | instruction | 0 | 40,470 | 12 | 80,940 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
from itertools import accumulate, permutations
R = lambda: map(int, input().split())
n = int(input())
acc = [0] + list(accumulate(R()))
for q in range(int(input())):
l, r = R()
print((acc[r] - acc[l - 1]) // 10)
``` | output | 1 | 40,470 | 12 | 80,941 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
Submitted Solution:
```
mod=10
n=int(input())
A=tuple(map(int,input().split()))
Acc=[0]*(n+1)
for i,a in enumerate(A):
Acc[i+1]=Acc[i]+a
q=int(input())
for _ in range(q):
l,r=map(int,input().split())
s=Acc[r]-Acc[l-1]
print((s-(s%mod))//mod)
``` | instruction | 0 | 40,471 | 12 | 80,942 |
Yes | output | 1 | 40,471 | 12 | 80,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
Submitted Solution:
```
i = int(input())
arr = [0]
line = input().split()
for x in range(i):
arr.append(int(line[x]) + arr[x])
q = int(input())
for x in range(q):
line = input().split()
print((arr[int(line[1])]-arr[int(line[0])-1])//10)
``` | instruction | 0 | 40,472 | 12 | 80,944 |
Yes | output | 1 | 40,472 | 12 | 80,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
Submitted Solution:
```
n=int(input())
l1=list(map(int,input().split()))
for i in range(1,len(l1)):
l1[i]=l1[i]+l1[i-1]
q=int(input())
for i in range(q):
n,m=map(int,input().split())
if(n==1):
print(l1[m-1]//10)
else:
print((l1[m-1]-l1[n-2])//10)
``` | instruction | 0 | 40,473 | 12 | 80,946 |
Yes | output | 1 | 40,473 | 12 | 80,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
Submitted Solution:
```
#Second try with the segment tree
import sys
input=sys.stdin.readline
n=int(input())
a=[int(x) for x in input().split()]
q=int(input())
seg=[[0,0] for i in range(4*n)]
def build(a,v,l,r,seg):
if l==r:
seg[v][0]=a[l]
else:
m=l+(r-l)//2
build(a,2*v+1,l,m,seg)
build(a,2*v+2,m+1,r,seg)
seg[v][0]=(seg[2*v+1][0]+seg[2*v+2][0])%10
seg[v][1]=seg[2*v+1][1]+seg[2*v+2][1]+(seg[2*v+1][0]+seg[2*v+2][0])//10
build(a,0,0,n-1,seg)
#print(seg)
def query(v,tl,tr,l,r,seg):
if l<=tl and r>=tr:
#print(v,l,r,seg[v])
return seg[v]
if tr<l or tl>r:
return [0,0]
tm=tl+(tr-tl)//2
z1=query(v*2+1,tl,tm,l,r,seg)
z2=query(2*v+2,tm+1,tr,l,r,seg)
z3=[(z1[0]+z2[0])%10,\
(z1[1]+z2[1])+(z1[0]+z2[0])//10]
#print(z3)
return z3
for i in range(q):
l,r=map(int,input().split())
print(query(0,0,n-1,l-1,r-1,seg)[1])
``` | instruction | 0 | 40,474 | 12 | 80,948 |
Yes | output | 1 | 40,474 | 12 | 80,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
# use odd and even SegTree
# node has(val %10,candies)
class SegmentTree():
def __init__(self, n, func, init=float('inf')):
self.n = 2**(n-1).bit_length()
self.init = init
self.data = [init]*(2*self.n)
self.func = func
def set(self, k, v):
self.data[k+self.n-1] = v
def build(self):
for k in reversed(range(self.n-1)):
self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])
def query(self, l, r):
L = l+self.n
R = r+self.n
ret = self.init
while L < R:
if R & 1:
R -= 1
ret = self.func(ret, self.data[R-1])
if L & 1:
ret = self.func(ret, self.data[L-1])
L += 1
L >>= 1
R >>= 1
return ret
N = int(input())
L = list(map(int, input().split()))
Q = int(input())
Query = [list(map(lambda x:int(x)-1, input().split())) for _ in range(Q)]
def func(a, b):
"""
a:(num,candie)
"""
a_val, a_candie = a
b_val, b_candie = b
new_val = (a_val+b_val) % 10
candie = a_candie+b_candie
if a_val+b_val >= 10:
candie += 1
return (new_val, candie)
Seg_even = SegmentTree(N, func, init=(0, 0))
Seg_odd = SegmentTree(N-1, func, init=(0, 0))
Seg_even.set(0, (L[0], 0))
for i, l in enumerate(L[1:], 1):
Seg_even.set(i, (L[i], 0))
Seg_odd.set(i, (L[i], 0))
Seg_even.build()
Seg_odd.build()
for query in Query:
l, r = query
if l % 2 == r % 2:
r_t = r
else:
r_t = r // 2*2
if l == r_t:
ret = (L[l], 0)
elif l % 2 == 0:
ret = Seg_even.query(l, r_t)
else:
ret = Seg_odd.query(l, r_t)
if r != r_t:
ret = func(ret, (L[r], 0))
print(ret[1])
``` | instruction | 0 | 40,475 | 12 | 80,950 |
No | output | 1 | 40,475 | 12 | 80,951 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
Submitted Solution:
```
N = int(input())
a = list(map(int, input().split()))
n = int(input())
prefsum = {}
for i in range(N):
if i == 0:
prefsum[i] = a[0]
else:
prefsum[i] = prefsum[i - 1] + a[i]
for _ in range(n):
l, r = map(int, input().split())
candies = (prefsum[r - 1] - prefsum[l - 1]) // 10
print(candies)
``` | instruction | 0 | 40,476 | 12 | 80,952 |
No | output | 1 | 40,476 | 12 | 80,953 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
# use odd and even SegTree
# node has(val %10,candies)
class SegmentTree():
def __init__(self, n, func, init=float('inf')):
self.n = 2**(n-1).bit_length()
self.init = init
self.data = [init]*(2*self.n)
self.func = func
def set(self, k, v):
self.data[k+self.n-1] = v
def build(self):
for k in reversed(range(self.n-1)):
self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])
def query(self, l, r):
L = l+self.n
R = r+self.n
ret = self.init
while L < R:
if R & 1:
R -= 1
ret = self.func(ret, self.data[R-1])
if L & 1:
ret = self.func(ret, self.data[L-1])
L += 1
L >>= 1
R >>= 1
return ret
N = int(input())
L = list(map(int, input().split()))
Q = int(input())
Query = [list(map(lambda x:int(x)-1, input().split())) for _ in range(Q)]
def func(a, b):
"""
a:(num,candie)
"""
a_val, a_candie = a
b_val, b_candie = b
new_val = (a_val+b_val) % 10
candie = a_candie+b_candie
if a_val+b_val >= 10:
candie += 1
return (new_val, candie)
Seg_even = SegmentTree(N, func, init=(0, 0))
Seg_odd = SegmentTree(N-1, func, init=(0, 0))
Seg_even.set(0, (L[0], 0))
for i, l in enumerate(L[1:], 1):
Seg_even.set(i, (L[i], 0))
Seg_odd.set(i-1, (L[i], 0))
Seg_even.build()
Seg_odd.build()
for query in Query:
l, r = query
if l % 2 == r % 2:
r_t = r
else:
r_t = r // 2*2
if l == r_t:
ret = (L[l], 0)
elif l % 2 == 0:
ret = Seg_even.query(l, r_t)
else:
ret = Seg_odd.query(l-1, r_t-1)
if r != r_t:
ret = func(ret, (L[r], 0))
print(ret[1])
``` | instruction | 0 | 40,477 | 12 | 80,954 |
No | output | 1 | 40,477 | 12 | 80,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth …, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, …, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 ≥ 10 and 9 + 4 ≥ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 ≥ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, … s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, …, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the sequence.
The second line contains n digits s_1, s_2, …, s_n (0 ≤ s_i ≤ 9).
The third line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, …, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] → [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 ≥ 10 → [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with it.
Submitted Solution:
```
if __name__ == '__main__':
n = int(input())
ss = map(int, input().split())
q = int(input())
acc = 0
sacc = []
for s in ss:
acc += s
sacc.append(acc)
for _ in range(q):
l, r = map(int, input().split())
print((sacc[r - 1] - sacc[l - 1])//10)
``` | instruction | 0 | 40,478 | 12 | 80,956 |
No | output | 1 | 40,478 | 12 | 80,957 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than once. | instruction | 0 | 40,591 | 12 | 81,182 |
Tags: math, sortings, two pointers
Correct Solution:
```
T = int(input().rstrip())
for tt in range(T):
n,k = list(map(int,input().rstrip().split(" ")))
arr = list(map(int,input().rstrip().split(" ")))
hsh = {}
for i in arr:
val = i%k
if val != 0:
hsh[val] = hsh.get(val,0) + 1
if len(hsh) == 0: print(0); continue
mx2 = -1
for mx in hsh:
val2 = k - mx
cnt = hsh[mx]-1
val3 = val2 + k*cnt + 1
if val3 > mx2:
mx2 = val3
print( mx2)
``` | output | 1 | 40,591 | 12 | 81,183 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than once. | instruction | 0 | 40,592 | 12 | 81,184 |
Tags: math, sortings, two pointers
Correct Solution:
```
t=int(input())
def function(s,k):
return (k-s%k)*(s%k!=0)
answer=[]
for _ in range(t):
n,k=map(int,input().split(' '))
a=[ function(x,k) for x in list(map(int,input().split(' ')))]
a.sort()
max_count=0
remainder=0
actual=0
count_actual=0
for i in range(n):
if actual!=a[i]:
if count_actual>=max_count or remainder==0:
max_count=count_actual
remainder=actual
actual=a[i]
count_actual=1
else:
count_actual+=1
# print(max_count,count_actual)
if count_actual>=max_count or remainder==0:
max_count=count_actual
remainder=actual
tmp=(k*(max_count-1)+remainder+1)*(remainder!=0)
answer.append(str(tmp))
print(('\n').join(answer))
``` | output | 1 | 40,592 | 12 | 81,185 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than once. | instruction | 0 | 40,593 | 12 | 81,186 |
Tags: math, sortings, two pointers
Correct Solution:
```
t = int(input())
for _ in range(t):
n,k = map(int,input().split())
a = list(map(int,input().split()))
new = []
d = {}
for i in range(n):
if a[i]%k == 0:
pass
else:
x = k - a[i]%k
if d.get(x):
y = d[x]*k + x
d[x] += 1
new.append(y)
else:
d[x] = 1
new.append(x)
print(max(new)+1 if len(new) else 0)
``` | output | 1 | 40,593 | 12 | 81,187 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than once. | instruction | 0 | 40,594 | 12 | 81,188 |
Tags: math, sortings, 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")
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 Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
n,k = Ri()
a = Ri()
dic= {}
maxx = -1
for i in a:
if i%k != 0:
dic[i%k] = dic.get(i%k, 0)+1
tmaxx = (dic[i%k]-1)*k + (k-i%k)
maxx = max(tmaxx, maxx)
print(maxx+1)
``` | output | 1 | 40,594 | 12 | 81,189 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than once. | instruction | 0 | 40,595 | 12 | 81,190 |
Tags: math, sortings, two pointers
Correct Solution:
```
def Solve():
n, k = input().split()
n, k = int(n), int(k)
a = input().split()
a = [int(x) for x in a]
dic = {}
c = 0
for i in range(len(a)):
x = (k-a[i]%k) % k
if x:
if dic.get(x) != None:
c = max(c, k * dic[x] + x + 1)
dic[x]+=1
else:
c = max(c, k * 0 + x + 1)
dic[x]=1
print(c)
q = int(input())
while q:
Solve()
q-=1
``` | output | 1 | 40,595 | 12 | 81,191 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than once. | instruction | 0 | 40,596 | 12 | 81,192 |
Tags: math, sortings, two pointers
Correct Solution:
```
t=int(input())
for _ in range(t):
di={}
n,k=map(int,input().split())
l=list(map(int,input().split()))
r=[0 if i%k==0 else (k-(i%k)) for i in l ]
#print(r)
for i in r:
if i>0:
if i in di:
di[i]+=1
else:
di[i]=1
c=0
v=0
for x,y in di.items():
if y>c:
c=y
v=x
elif y==c:
if v<x:
v=x
ans=max(0,(v+((c-1)*k)+1))
print(ans)
``` | output | 1 | 40,596 | 12 | 81,193 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than once. | instruction | 0 | 40,597 | 12 | 81,194 |
Tags: math, sortings, two pointers
Correct Solution:
```
from collections import Counter
cases = int(input())
for t in range(cases):
n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
rem = []
for i in a:
d = i%k
if d!=0:
d = k-d
rem.append(d)
if rem:
a = Counter(rem)
key,val = 0,0
for i,v in a.items():
if v>val:
val = v
key=i
elif v==val:
key=max(key,i)
print(key+(val-1)*k+1)
else:
print(0)
``` | output | 1 | 40,597 | 12 | 81,195 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than once. | instruction | 0 | 40,598 | 12 | 81,196 |
Tags: math, sortings, two pointers
Correct Solution:
```
# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-29 18:43
# @url:https://codeforc.es/contest/1374/problem/D
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio
BUFSIZE = 8192
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 main():
t=int(input())
for i in range(t):
n,k=map(int,input().split())
a=list(map(int,input().split()))
m=[]
for j in a:
m.append(k-(j%k))
sm=sorted([x for x in m if x!=k])
d=collections.Counter(sm)
if len(sm)==0:
print (0)
continue
# both loop and sort can ac
# 1.
# for key in d.keys():
# if d[key]>1:
# temp=key+(d[key]-1)*k
# if temp>mx:
# mx=temp
# 2.
sd=sorted(d.items(),key=lambda x: (x[1],x[0]))
key=sd[-1][0]
print (key+(d[key]-1)*k+1)
if __name__ == "__main__":
main()
``` | output | 1 | 40,598 | 12 | 81,197 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.