text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.
You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.
For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 → 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.
Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 3000) — the number of digits in the original number.
The second line of each test case contains a non-negative integer number s, consisting of n digits.
It is guaranteed that s does not contain leading zeros and the sum of n over all test cases does not exceed 3000.
Output
For each test case given in the input print the answer in the following format:
* If it is impossible to create an ebne number, print "-1" (without quotes);
* Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.
Example
Input
4
4
1227
1
0
6
177013
24
222373204424185217171912
Output
1227
-1
17703
2237344218521717191
Note
In the first test case of the example, 1227 is already an ebne number (as 1 + 2 + 2 + 7 = 12, 12 is divisible by 2, while in the same time, 1227 is not divisible by 2) so we don't need to delete any digits. Answers such as 127 and 17 will also be accepted.
In the second test case of the example, it is clearly impossible to create an ebne number from the given number.
In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 1 digit such as 17703, 77013 or 17013. Answers such as 1701 or 770 will not be accepted as they are not ebne numbers. Answer 013 will not be accepted as it contains leading zeroes.
Explanation:
* 1 + 7 + 7 + 0 + 3 = 18. As 18 is divisible by 2 while 17703 is not divisible by 2, we can see that 17703 is an ebne number. Same with 77013 and 17013;
* 1 + 7 + 0 + 1 = 9. Because 9 is not divisible by 2, 1701 is not an ebne number;
* 7 + 7 + 0 = 14. This time, 14 is divisible by 2 but 770 is also divisible by 2, therefore, 770 is not an ebne number.
In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 → 22237320442418521717191 (delete the last digit).
Submitted Solution:
```
for i in range(int(input())):
n = int(input())
s = list(input())
ans = ""
suma = 0
t = 0
for i in range(n):
suma += int(s[i])
ans += s[i]
if suma % 2 == 0 and int(s[i]) % 2 == 1:
print(ans)
t = 1
break
if t == 0:
print(-1)
continue
```
Yes
| 89,400 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.
You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.
For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 → 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.
Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 3000) — the number of digits in the original number.
The second line of each test case contains a non-negative integer number s, consisting of n digits.
It is guaranteed that s does not contain leading zeros and the sum of n over all test cases does not exceed 3000.
Output
For each test case given in the input print the answer in the following format:
* If it is impossible to create an ebne number, print "-1" (without quotes);
* Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.
Example
Input
4
4
1227
1
0
6
177013
24
222373204424185217171912
Output
1227
-1
17703
2237344218521717191
Note
In the first test case of the example, 1227 is already an ebne number (as 1 + 2 + 2 + 7 = 12, 12 is divisible by 2, while in the same time, 1227 is not divisible by 2) so we don't need to delete any digits. Answers such as 127 and 17 will also be accepted.
In the second test case of the example, it is clearly impossible to create an ebne number from the given number.
In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 1 digit such as 17703, 77013 or 17013. Answers such as 1701 or 770 will not be accepted as they are not ebne numbers. Answer 013 will not be accepted as it contains leading zeroes.
Explanation:
* 1 + 7 + 7 + 0 + 3 = 18. As 18 is divisible by 2 while 17703 is not divisible by 2, we can see that 17703 is an ebne number. Same with 77013 and 17013;
* 1 + 7 + 0 + 1 = 9. Because 9 is not divisible by 2, 1701 is not an ebne number;
* 7 + 7 + 0 = 14. This time, 14 is divisible by 2 but 770 is also divisible by 2, therefore, 770 is not an ebne number.
In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 → 22237320442418521717191 (delete the last digit).
Submitted Solution:
```
t=int(input())
for i in range(t):
e=int(input())
st=input()
odd=0
pti=0
ind=[0]*e
for j in range(e):
if int(st[j])%2==1:
ind[j]=1
odd+=1
if odd%2==0 and odd>1:
pti=j
break
if pti==0:
print(-1)
continue
for k in range(pti+1):
print(st[k],end="")
print()
```
Yes
| 89,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.
You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.
For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 → 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.
Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 3000) — the number of digits in the original number.
The second line of each test case contains a non-negative integer number s, consisting of n digits.
It is guaranteed that s does not contain leading zeros and the sum of n over all test cases does not exceed 3000.
Output
For each test case given in the input print the answer in the following format:
* If it is impossible to create an ebne number, print "-1" (without quotes);
* Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.
Example
Input
4
4
1227
1
0
6
177013
24
222373204424185217171912
Output
1227
-1
17703
2237344218521717191
Note
In the first test case of the example, 1227 is already an ebne number (as 1 + 2 + 2 + 7 = 12, 12 is divisible by 2, while in the same time, 1227 is not divisible by 2) so we don't need to delete any digits. Answers such as 127 and 17 will also be accepted.
In the second test case of the example, it is clearly impossible to create an ebne number from the given number.
In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 1 digit such as 17703, 77013 or 17013. Answers such as 1701 or 770 will not be accepted as they are not ebne numbers. Answer 013 will not be accepted as it contains leading zeroes.
Explanation:
* 1 + 7 + 7 + 0 + 3 = 18. As 18 is divisible by 2 while 17703 is not divisible by 2, we can see that 17703 is an ebne number. Same with 77013 and 17013;
* 1 + 7 + 0 + 1 = 9. Because 9 is not divisible by 2, 1701 is not an ebne number;
* 7 + 7 + 0 = 14. This time, 14 is divisible by 2 but 770 is also divisible by 2, therefore, 770 is not an ebne number.
In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 → 22237320442418521717191 (delete the last digit).
Submitted Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
N = int(input())
S = list(map(int, list(input())[: -1]))
for i in range(N - 1, -1, -1):
if S[i] % 2: break
S.pop()
N = len(S)
sm = sum(S)
for i in range(N - 1, -1, -1):
if sm % 2 == 0: break
if S[i] % 2:
S.pop(i)
break
if len(S):
print("".join(list(map(str, S))))
else: print(-1)
```
No
| 89,402 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.
You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.
For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 → 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.
Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 3000) — the number of digits in the original number.
The second line of each test case contains a non-negative integer number s, consisting of n digits.
It is guaranteed that s does not contain leading zeros and the sum of n over all test cases does not exceed 3000.
Output
For each test case given in the input print the answer in the following format:
* If it is impossible to create an ebne number, print "-1" (without quotes);
* Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.
Example
Input
4
4
1227
1
0
6
177013
24
222373204424185217171912
Output
1227
-1
17703
2237344218521717191
Note
In the first test case of the example, 1227 is already an ebne number (as 1 + 2 + 2 + 7 = 12, 12 is divisible by 2, while in the same time, 1227 is not divisible by 2) so we don't need to delete any digits. Answers such as 127 and 17 will also be accepted.
In the second test case of the example, it is clearly impossible to create an ebne number from the given number.
In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 1 digit such as 17703, 77013 or 17013. Answers such as 1701 or 770 will not be accepted as they are not ebne numbers. Answer 013 will not be accepted as it contains leading zeroes.
Explanation:
* 1 + 7 + 7 + 0 + 3 = 18. As 18 is divisible by 2 while 17703 is not divisible by 2, we can see that 17703 is an ebne number. Same with 77013 and 17013;
* 1 + 7 + 0 + 1 = 9. Because 9 is not divisible by 2, 1701 is not an ebne number;
* 7 + 7 + 0 = 14. This time, 14 is divisible by 2 but 770 is also divisible by 2, therefore, 770 is not an ebne number.
In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 → 22237320442418521717191 (delete the last digit).
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
lst=list(input())
if int(lst[-1])%2==0:
lst.pop(-1)
sum=0
for i in lst:
sum+=int(i)
if sum==0:
print(-1)
elif sum%2==0:
print(''.join(lst))
else:
flag=1
for i in range(len(lst)):
if int(lst[i])%2==1:
lst.pop(i)
flag=0
break
if flag==1:
print(-1)
else:
print(''.join(lst))
```
No
| 89,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.
You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.
For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 → 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.
Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 3000) — the number of digits in the original number.
The second line of each test case contains a non-negative integer number s, consisting of n digits.
It is guaranteed that s does not contain leading zeros and the sum of n over all test cases does not exceed 3000.
Output
For each test case given in the input print the answer in the following format:
* If it is impossible to create an ebne number, print "-1" (without quotes);
* Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.
Example
Input
4
4
1227
1
0
6
177013
24
222373204424185217171912
Output
1227
-1
17703
2237344218521717191
Note
In the first test case of the example, 1227 is already an ebne number (as 1 + 2 + 2 + 7 = 12, 12 is divisible by 2, while in the same time, 1227 is not divisible by 2) so we don't need to delete any digits. Answers such as 127 and 17 will also be accepted.
In the second test case of the example, it is clearly impossible to create an ebne number from the given number.
In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 1 digit such as 17703, 77013 or 17013. Answers such as 1701 or 770 will not be accepted as they are not ebne numbers. Answer 013 will not be accepted as it contains leading zeroes.
Explanation:
* 1 + 7 + 7 + 0 + 3 = 18. As 18 is divisible by 2 while 17703 is not divisible by 2, we can see that 17703 is an ebne number. Same with 77013 and 17013;
* 1 + 7 + 0 + 1 = 9. Because 9 is not divisible by 2, 1701 is not an ebne number;
* 7 + 7 + 0 = 14. This time, 14 is divisible by 2 but 770 is also divisible by 2, therefore, 770 is not an ebne number.
In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 → 22237320442418521717191 (delete the last digit).
Submitted Solution:
```
for _ in range(int(input())):
length = int(input())
number = input()
count = 0
for i in range(length):
if int(number[i]) % 2:
count += 1
print("YES" if count > 1 else "NO")
```
No
| 89,404 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.
You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.
For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 → 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.
Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 3000) — the number of digits in the original number.
The second line of each test case contains a non-negative integer number s, consisting of n digits.
It is guaranteed that s does not contain leading zeros and the sum of n over all test cases does not exceed 3000.
Output
For each test case given in the input print the answer in the following format:
* If it is impossible to create an ebne number, print "-1" (without quotes);
* Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.
Example
Input
4
4
1227
1
0
6
177013
24
222373204424185217171912
Output
1227
-1
17703
2237344218521717191
Note
In the first test case of the example, 1227 is already an ebne number (as 1 + 2 + 2 + 7 = 12, 12 is divisible by 2, while in the same time, 1227 is not divisible by 2) so we don't need to delete any digits. Answers such as 127 and 17 will also be accepted.
In the second test case of the example, it is clearly impossible to create an ebne number from the given number.
In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 1 digit such as 17703, 77013 or 17013. Answers such as 1701 or 770 will not be accepted as they are not ebne numbers. Answer 013 will not be accepted as it contains leading zeroes.
Explanation:
* 1 + 7 + 7 + 0 + 3 = 18. As 18 is divisible by 2 while 17703 is not divisible by 2, we can see that 17703 is an ebne number. Same with 77013 and 17013;
* 1 + 7 + 0 + 1 = 9. Because 9 is not divisible by 2, 1701 is not an ebne number;
* 7 + 7 + 0 = 14. This time, 14 is divisible by 2 but 770 is also divisible by 2, therefore, 770 is not an ebne number.
In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 → 22237320442418521717191 (delete the last digit).
Submitted Solution:
```
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the function below.
def function(a,b):
d= [int(x) if int(x)%2!=0 else int(0) for x in b]
ans= ' '.join([str(elem) for elem in d])
ans=ans.replace("0","")
ans=ans.replace(" ","")
if ans=="":
print(-1)
else:
print(ans)
count=int(input())
i=0
while i!=count:
a=int(input())
b= list(input())
function(a,b)
i=i+1
```
No
| 89,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Tags: dfs and similar, sortings
Correct Solution:
```
#### Using DSU..... best time complexity
def find(x):
while(x != link[x]):
link[x] = link[link[x]]
x = link[x]
return x
def union(x, y):
x = find(x)
y = find(y)
if x != y:
if size[x] > size[y]:
size[x] += size[y]
link[y] = x
else:
size[y] += size[x]
link[x] = y
for _ in range(int(input())):
n,m = list(map(int, input().split()))
array = list(map(int, input().split()))
piss = list(map(int, input().split()))
for i in range(n):
array[i] = (array[i], i)
array.sort()
link = list(range(n))
size = [1]*n
for i in piss:
union(i-1, i)
flag = True
for i in range(n):
if find(i) != find(array[i][1]):
flag = False
break
if flag:
print('YES')
else:
print('NO')
```
| 89,406 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Tags: dfs and similar, sortings
Correct Solution:
```
# import sys
# sys.stdin = open("input.in","r")
# sys.stdout = open("output.out","w")
from collections import defaultdict
t = int(input())
for i in range(t):
n,m = map(int,input().split())
a = list(map(int,input().split()))
p = list(map(int,input().split()))
p = [p[j]-1 for j in range(m)]
r = sorted(a)
d = set()
for j in p:
d.add(j)
flag = 0
for j in range(n):
z = a[j:].index(r[j])
z = z + j
if z > j:
for k in range(z,j,-1):
if k-1 in d:
a[k-1],a[k] = a[k],a[k-1]
else:
flag = 1
break
else:
for k in range(j,z,-1):
if k-1 in d:
a[k-1],a[k] = a[k],a[k-1]
else:
flag = 1
break
if flag == 1:
break
if flag == 1:
print("NO")
else:
print("YES")
```
| 89,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Tags: dfs and similar, sortings
Correct Solution:
```
import sys
sys.setrecursionlimit(10 ** 6)
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 LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def main():
t=II()
for _ in range(t):
n,m=MI()
aa=LI()
pp=LI1()
bb=[]
cur=[]
for p in sorted(pp):
if not cur:
if p>0:bb+=aa[:p]
cur=[p]
elif p==cur[-1]+1:
cur.append(p)
else:
bb+=sorted(aa[cur[0]:cur[-1]+2])
bb+=aa[cur[-1]+2:p]
cur=[p]
bb+=sorted(aa[cur[0]:cur[-1]+2])
bb+=aa[cur[-1]+2:]
aa.sort()
if aa==bb:print("YES")
else:print("NO")
main()
```
| 89,408 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Tags: dfs and similar, sortings
Correct Solution:
```
from collections import defaultdict
t = int(input().strip())
class Graph:
def __init__(self, V):
self.V = V+1
self.edges = defaultdict(list)
def addEdge(self, u, v):
if v not in self.edges[u]:
self.edges[u].append(v)
def DFS(self, source, destination):
visited = [False]*self.V
stack = []
stack.append(source)
while (len(stack)):
s = stack.pop()
if s == destination:
return True
if (not visited[s]):
visited[s] = True
for node in self.edges[s]:
if (not visited[node]):
stack.append(node)
return False
for _ in range(t):
n, m = list(map(int, input().strip().split()))
arr_n = list(map(int, input().strip().split()))
arr = list(zip(arr_n, range(1, n+1)))
arr.sort()
arr_m = list(map(int, input().strip().split()))
arr_m.sort()
g = Graph(n)
for i in range(m):
j = arr_m[i]
g.addEdge(j,j+1)
g.addEdge(j+1,j)
# print(g.edges)
for i in range(n):
if not g.DFS(i+1,arr[i][1]):
print("NO")
break
else:
print("YES")
```
| 89,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Tags: dfs and similar, sortings
Correct Solution:
```
for i in range(int(input())):
n,m = map(int,input().split())
arr1 = list(map(int,input().split()))
arr2 = list(map(int,input().split()))
sorted(arr2)
for k in range(n):
for j in arr2:
if arr1[j-1]>arr1[j]:
arr1[j-1],arr1[j]=arr1[j],arr1[j-1]
if arr1 ==sorted(arr1):
print("YES")
else:
print("NO")
```
| 89,410 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Tags: dfs and similar, sortings
Correct Solution:
```
t = int(input())
for _ in range(t):
n, m = [int(i) for i in input().split()]
arr = [int(i) for i in input().split()]
p = [int(i) for i in input().split()]
p.sort()
i = 0
while i < m:
temp = p[i]
k = i+1
while k < m:
if p[k] != temp+1:
break
else:
temp = p[k]
k += 1
arr[p[i]-1:p[k-1]+1] = sorted(arr[p[i]-1:p[k-1]+1])
i = k
if arr == sorted(arr):
print("YES")
else:
print("NO")
```
| 89,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Tags: dfs and similar, sortings
Correct Solution:
```
# import sys
# sys.stdin=open('input.txt', 'r')
# sys.stdout=open('output.txt', 'w')
n=int(input())
for i in range(n):
n, m=[int(k) for k in input().split()]
a=[int(k) for k in input().split()]
p=[int(k)-1 for k in input().split()]
sor=sorted(a)
can=None
ori=list(a)
ant=list(a)
while a!=sor:
for j in range(len(p)):
if a[p[j]]>a[p[j]+1]:
aux=a[p[j]]
a[p[j]]=a[p[j]+1]
a[p[j]+1]=aux
if a==sor: break
if a==sor:
can=True
break
if a==ori:
can=False
break
if ant==a:
can=False
break
else: ant=list(a)
if a==sor: can=True
if can: print('YES')
else: print('NO')
```
| 89,412 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Tags: dfs and similar, sortings
Correct Solution:
```
for t in range(int(input())):
n,m=map(int,input().split())
a=list(map(int,input().split()))
p=list(map(int,input().split()))
mark=True
for i in range(n):
for j in range(n-i-1):
if a[j]>a[j+1]:
if j+1 in p:
a[j],a[j+1]=a[j+1],a[j]
else:
mark=False
break
if mark==False:
print("NO")
else:
print("YES")
```
| 89,413 |
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 length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Submitted Solution:
```
t = int(input())
for i in range(t):
n, m = map(int,input().split())
a = list(map(int,input().split()))
p = list(map(int,input().split()))
b = sorted(a)
f = 0
for k in range(n):
for j in range(n-k-1):
if (a[j] > a[j+1] and (j+1) in p):
tmp = a[j]
a[j] = a[j+1]
a[j+1] = tmp
if(b == a):
print('YES')
else:
print('NO')
```
Yes
| 89,414 |
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 length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Submitted Solution:
```
te = int(input())
while te > 0:
te -= 1
x, y = list(map(int, input().split()))
numbers = list(map(int, input().split()))
positions = list(map(int, input().split()))
pos = [0]*x
for i in positions:
pos[i-1] = 1
# print(pos)
while True:
ok = False
for j in range(x-1):
if pos[j] == 1 and numbers[j] > numbers[j+1]:
ok = True
a = numbers[j]
numbers[j] = numbers[j+1]
numbers[j+1] = a
if not ok:
break
# print(numbers)
ok = True
for i in range(x-1):
ok &= numbers[i] <= numbers[i+1]
if ok:
print('Yes')
else:
print('No')
```
Yes
| 89,415 |
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 length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Submitted Solution:
```
def go():
n, m = map(int, input().split())
a = list(map(int, input().split()))
p = sorted(map(int, input().split()))
sa = sorted(a)
i = 0
pp = 0
while i < n:
j = i
while j < n and pp < m and p[pp] - 1 == j:
j += 1
pp += 1
if sorted(a[i:j + 1]) != sa[i:j + 1]:
return 'NO'
i = j + 1
return 'YES'
t = int(input())
ans = []
for _ in range(t):
ans.append(str(go()))
print('\n'.join(ans))
```
Yes
| 89,416 |
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 length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Submitted Solution:
```
for _ in range(int(input())):
n, m = map(int ,input().split())
a = list(map(int, input().split()))
p = list(map(int, input().split()))
p.sort()
for i in range(n):
for j in p:
if (a[j-1] > a[j]):
a[j-1], a[j] = a[j], a[j-1]
if a != sorted(a):
print("NO")
else:
print("YES")
```
Yes
| 89,417 |
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 length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Submitted Solution:
```
def main():
t = int(input())
for query in range(t):
N, M = (int(i) for i in input().split())
par = [i for i in range(105)]
rank = [0 for i in range(105)]
def find_root(x):
if par[x] == x:
return x
else:
par[x] = find_root(par[x])
return par[x]
def is_same_group(x, y):
return find_root(x) == find_root(y)
def unite(x, y):
x = find_root(x)
y = find_root(y)
if x == y:
return
if rank[x] < rank[y]:
par[x] = y
else:
par[y] = x
if rank[x] == rank[y]:
rank[x] += 1
A = [int(i) for i in input().split()]
P = [int(i) for i in input().split()]
for p in P:
unite(p, p+1)
pre = A[0]
for i, a in enumerate(A):
if is_same_group(i+1, a) or pre <= a:
pre = a
continue
else:
print("NO")
break
else:
print("YES")
if __name__ == '__main__':
main()
```
No
| 89,418 |
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 length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Submitted Solution:
```
for _ in range(int(input())):
n,m = map(int,input().split())
a = list(map(int,input().split()))
p = list(map(int,input().split()))
d = {}
for i in range(len(a)):
x = i+1
if x in p:
d[i] = i+1
else:
d[i] = i
o = a.copy()
o.sort()
o = o[::-1]
i = 0
c = len(a)-1
w = 0
while(i < len(o)):
x = o[i]
ei = a.index(x)
#print(ei)
f = 0
while(ei != c and f == 0):
z = d[ei]
if z >= c:
ei = c
break
if (ei == z):
f = 1
else:
ei = z
if ei == c:
#print("Y")
c = c-1
else:
w = 1
break
i = i+1
if w == 1:
print("NO")
else:
print("YES")
```
No
| 89,419 |
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 length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Submitted Solution:
```
t=int(input())
for _ in range(t):
n,m=[int(x) for x in input().split()]
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
j=0
while(j<(n-1)):
if(a[j]>a[j+1]):
if(j+1 in b):
temp=a[j+1]
a[j+1]=a[j]
a[j]=temp
else:
break
j+=1
if(j==len(a)-1):
print('YES')
else:
print('NO')
```
No
| 89,420 |
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 length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps.
For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t test cases follow. The first line of each test case contains two integers n and m (1 ≤ m < n ≤ 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100). The third line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n, all p_i are distinct) — the set of positions described in the problem statement.
Output
For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 ≤ a_2 ≤ ... ≤ a_n) using only allowed swaps. Otherwise, print "NO".
Example
Input
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
Submitted Solution:
```
t=int(input())
while(t!=0):
t-=1
n,m=map(int,input().split())
a=list(map(int,input().split()))
p=list(map(int,input().split()))
v=[]
for i in range(n-1):
if a[i+1]<a[i]:
v.append(i+1)
ans=True
for i in v:
if i not in p:
ans=False
break
if ans:
print("YES")
else:
print("NO")
```
No
| 89,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
n = int(input())
res = [1] * (n + 1)
for i in range(2, n + 1):
j = i
while i*j <= n:
res[i*j] = max(res[i*j], j)
j += 1
res.sort()
print(" ".join(map(str, res[2:])))
```
| 89,422 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
from sys import stdin, stdout
input = stdin.readline
print = stdout.write
R = lambda: list(map(int, input().split()))
n = int(input())
s = [0]*(n+1)
vis = [0]*(n+1)
u = 2
while u*u <= n:
if not vis[u]:
for i in range(u*2, n+1, u):
if vis[i]: continue
vis[i] = 1
s[i//u] += 1
u += 1
for i in range(2, n+1):
if not vis[i]: s[1] += 1
res = []
for i in range(n+1):
if s[i] > 0: res.append((str(i)+' ')*s[i])
print(''.join(res))
```
| 89,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
n = int(input())
sieve = [-1] * (n + 1)
primes = []
for i in range(2, n + 1):
if sieve[i] == -1:
sieve[i] = i
primes.append(i)
for x in range(2 * i, n + 1, i):
if sieve[x] == -1:
sieve[x] = i
answer = [1] * len(primes)
c = set(primes)
c.add(1)
toAdd = 2
while len(c) != n:
for k in primes:
if k > sieve[toAdd]:
break
y = toAdd * k
if y > n:
break
if y not in c:
c.add(y)
answer.append(toAdd)
toAdd += 1
print(*answer)
```
| 89,424 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
def lf(x):
i = 2
while i * i <= x:
if x % i == 0: return x // i
i += 1
return 1
if __name__ == "__main__":
n = int(input())
d = []
for i in range(2, n + 1):
#print(i, lf(i), sep = ' ')
d.append(lf(i))
d.sort()
print(' '.join(map(str, d)))
```
| 89,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
def main():
for _ in inputt(1):
n, = inputi()
S = [1] * (n + 1)
for i in range(2, n // 2 + 1):
for j in range(i * 2, n + 1, i):
S[j] = i
S.sort()
print(*S[2:])
# region M
# region fastio
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(io.IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
for x in args:
file.write(str(x))
file.write(kwargs.pop("end", "\n"))
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
# region import
inputt = lambda t = 0: range(t) if t else range(int(input()))
inputi = lambda: map(int, input().split())
inputl = lambda: list(inputi())
from math import *
from heapq import *
from bisect import *
from itertools import *
from functools import reduce, lru_cache
from collections import Counter, defaultdict
import re, copy, operator, cmath
from builtins import *
# endregion
# region main
if __name__ == "__main__":
main()
# endregion
# endregion
```
| 89,426 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
n = int(input())
l = [0]*(n+1)
for i in range(1,n+1):
for j in range(2*i,n+1,i):
l[j] = i
l.sort()
print(*l[2:n+1])
```
| 89,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 2020/7/1
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
if __name__ == '__main__':
N = int(input())
# t0 = time.time()
maxdiv = [0 for _ in range(N+1)]
maxdiv[1] = 1
# print(time.time() - t0)
for i in range(2, N+1):
if maxdiv[i]:
continue
v = i
d = 1
while v <= N:
if maxdiv[v] == 0:
maxdiv[v] = d
v += i
d += 1
# print(time.time() - t0)
maxdiv = maxdiv[1:]
maxdiv.sort()
# print(time.time() - t0)
ans = []
maxd = 0
for v in maxdiv:
maxd = max(maxd, v)
ans.append(maxd)
print(' '.join(map(str, ans[1:])))
# print(time.time() - t0)
```
| 89,428 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
n = int(input())
ans=[1]*(n+1)
for i in range(2,n+1):
j=i
while j*i<=n:
ans[j*i]=max(ans[j*i],j)
j+=1
a=sorted(ans)
print(*a[2:])
```
| 89,429 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Tags: greedy, implementation, math, number theory, sortings, two pointers
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
for i in arr:
stdout.write(str(i)+' ')
stdout.write('\n')
range = xrange # not for python 3.0+
n=int(raw_input())
arr=[1]*(n+1)
for i in range(2,n+1):
for j in range(2*i,n+1,i):
arr[j]=i
arr=arr[2:]
arr.sort()
pr(' '.join(map(str,arr)))
#pr_arr(arr)
```
| 89,430 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Submitted Solution:
```
n = int(input())
A = [1 for i in range(n+1)]
for i in range(2, n):
j = 2*i
while j <= n:
A[j] = i
j += i
ans = sorted(A)
ans = ans[2:]
print(*ans)
```
Yes
| 89,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Submitted Solution:
```
def solve(n):
nums = [1] * (n + 1)
p = 2
while p * p <= n:
if nums[p] == 1:
for i in range(p * 2, n+1, p):
nums[i] = max(nums[i], p, i // p)
p += 1
return sorted(sorted(nums[2:]))
n = int(input())
print(' '.join([str(x) for x in solve(n)]))
```
Yes
| 89,432 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Submitted Solution:
```
def get_primes(n):
res = [2]
arr = [True] * ((n - 1) // 2)
i = 0
for i in range(len(arr)):
if arr[i]:
a = i * 2 + 3
res.append(a)
for ii in range(i + a, len(arr), a):
arr[ii] = False
return res
if __name__ == "__main__":
n = int(input())
primes = get_primes(n)
res = ["1"] * min(n - 1, len(primes))
left = n - 1 - len(res)
ii = 2
while left > 0:
for a in primes:
if ii * a <= n:
res.append(str(ii))
left -= 1
else:
break
if ii % a == 0 or left == 0:
break
ii += 1
print(" ".join(res))
```
Yes
| 89,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
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 not True else 1):
n = int(input())
imp = n // 2
ans = [1]*(n + 1)
used = [False]*(n+1)
cur = n
while imp > 1:
first = False
for i in range(imp, n+1, imp):
if not used[i]:
if not first:
first = True
else:
used[i] = True
#print(imp)
ans[cur] = imp
cur -= 1
imp -= 1
print(*ans[2:])
```
Yes
| 89,434 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Submitted Solution:
```
import sys
input=sys.stdin.readline
n=int(input())
sum=1
if n%2==0:
for _ in range(n//2):
print(sum,end=' ')
z=(n-1)-n//2
for _ in range(z):
sum+=1
print(sum,end=' ')
else:
for _ in range((n+1)//2):
print(sum,end=' ')
z=(n-1)-(n+1)//2
for _ in range(z):
sum+=1
print(sum,end=' ')
```
No
| 89,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Submitted Solution:
```
n = int(input())
print(*[1] * (n - 1))
```
No
| 89,436 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Submitted Solution:
```
def main():
for _ in inputt(1):
n, = inputi()
S = [1] * (n + 1)
for i in range(2, n // 2 + 1):
for j in range(i * 2, n + 1, i):
S[j] = i
print(*S[2:])
# region M
# region fastio
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(io.IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
for x in args:
file.write(str(x))
file.write(kwargs.pop("end", "\n"))
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
# region import
inputt = lambda t = 0: range(t) if t else range(int(input()))
inputi = lambda: map(int, input().split())
inputl = lambda: list(inputi())
from math import *
from heapq import *
from bisect import *
from itertools import *
from functools import reduce, lru_cache
from collections import Counter, defaultdict
import re, copy, operator, cmath
from builtins import *
# endregion
# region main
if __name__ == "__main__":
main()
# endregion
# endregion
```
No
| 89,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k.
Please, help Kate to find I_2, I_3, ..., I_n.
Input
The first and only line in the input consists of only one integer n (2≤ n ≤ 5 ⋅ 10^5) — the size of the given set S.
Output
Output contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.
Examples
Input
2
Output
1
Input
3
Output
1 1
Note
First sample: answer is 1, because gcd(1, 2) = 1.
Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}.
Submitted Solution:
```
n = int(input())
P = set()
for k in range(2, n + 1):
prime = True
for p in P:
if k % p == 0:
prime = False
break
if prime:
P.add(k)
ans = []
R = set()
for p in P:
ans.append(1)
R.add(p)
Q = []
for i in range(2, n // 2 + 1):
if i in P:
Q.append(i)
for q in Q:
if i * q <= n and i * q not in R:
ans.append(i)
R.add(i * q)
print(' '.join(map(str, ans)))
if (len(ans) == n - 1):
print('ok', file=__import__('sys').stderr)
```
No
| 89,438 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Tags: binary search, geometry, math, ternary search
Correct Solution:
```
MOD = 10 ** 9 + 7
RLIMIT = 1000
DEBUG = 1
def main():
for _ in inputt():
n, = inputi()
d = 2 * pi / (n * 2)
s = 0
for i in range(1, 2 * n + 1):
if sin(i * d + pi / 4) > 0:
s += sin(i * d + pi / 4)
print(s)
# region M
# region import
from math import *
from heapq import *
from itertools import *
from functools import reduce, lru_cache, partial
from collections import Counter, defaultdict, deque
import re, copy, operator, cmath
import sys, io, os, builtins
sys.setrecursionlimit(RLIMIT)
# endregion
# region fastio
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(io.IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
if args:
sys.stdout.write(str(args[0]))
split = kwargs.pop("split", " ")
for arg in args[1:]:
sys.stdout.write(split)
sys.stdout.write(str(arg))
sys.stdout.write(kwargs.pop("end", "\n"))
def debug(*args, **kwargs):
if DEBUG and not __debug__:
print("debug", *args, **kwargs)
sys.stdout.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip()
inputt = lambda t = 0: range(t) if t else range(int(input()))
inputs = lambda: input().split()
inputi = lambda k = int: map(k, inputs())
inputl = lambda t = 0, k = lambda: list(inputi()): [k() for _ in range(t)] if t else list(k())
# endregion
# region bisect
def len(a):
if isinstance(a, range):
return -((a.start - a.stop) // a.step)
return builtins.len(a)
def bisect_left(a, x, key = None, lo = 0, hi = None):
if lo < 0: lo = 0
if hi == None: hi = len(a)
if key == None: key = do_nothing
while lo < hi:
mid = (lo + hi) // 2
if key(a[mid]) < x: lo = mid + 1
else: hi = mid
return lo
def bisect_right(a, x, key = None, lo = 0, hi = None):
if lo < 0: lo = 0
if hi == None: hi = len(a)
if key == None: key = do_nothing
while lo < hi:
mid = (lo + hi) // 2
if x < key(a[mid]): hi = mid
else: lo = mid + 1
return lo
def insort_left(a, x, key = None, lo = 0, hi = None):
lo = bisect_left(a, x, key, lo, hi)
a.insert(lo, x)
def insort_right(a, x, key = None, lo = 0, hi = None):
lo = bisect_right(a, x, key, lo, hi)
a.insert(lo, x)
do_nothing = lambda x: x
bisect = bisect_right
insort = insort_right
def index(a, x, default = None, key = None, lo = 0, hi = None):
if lo < 0: lo = 0
if hi == None: hi = len(a)
if key == None: key = do_nothing
i = bisect_left(a, x, key, lo, hi)
if lo <= i < hi and key(a[i]) == x: return a[i]
if default != None: return default
raise ValueError
def find_lt(a, x, default = None, key = None, lo = 0, hi = None):
if lo < 0: lo = 0
if hi == None: hi = len(a)
i = bisect_left(a, x, key, lo, hi)
if lo < i <= hi: return a[i - 1]
if default != None: return default
raise ValueError
def find_le(a, x, default = None, key = None, lo = 0, hi = None):
if lo < 0: lo = 0
if hi == None: hi = len(a)
i = bisect_right(a, x, key, lo, hi)
if lo < i <= hi: return a[i - 1]
if default != None: return default
raise ValueError
def find_gt(a, x, default = None, key = None, lo = 0, hi = None):
if lo < 0: lo = 0
if hi == None: hi = len(a)
i = bisect_right(a, x, key, lo, hi)
if lo <= i < hi: return a[i]
if default != None: return default
raise ValueError
def find_ge(a, x, default = None, key = None, lo = 0, hi = None):
if lo < 0: lo = 0
if hi == None: hi = len(a)
i = bisect_left(a, x, key, lo, hi)
if lo <= i < hi: return a[i]
if default != None: return default
raise ValueError
# endregion
# region csgraph
# TODO
class Tree:
def __init__(n):
self._n = n
self._conn = [[] for _ in range(n)]
self._list = [0] * n
def connect(a, b):
pass
# endregion
# region ntheory
class Sieve:
def __init__(self):
self._n = 6
self._list = [2, 3, 5, 7, 11, 13]
def extend(self, n):
if n <= self._list[-1]: return
maxbase = int(n ** 0.5) + 1
self.extend(maxbase)
begin = self._list[-1] + 1
newsieve = [i for i in range(begin, n + 1)]
for p in self.primerange(2, maxbase):
for i in range(-begin % p, len(newsieve), p):
newsieve[i] = 0
self._list.extend([x for x in newsieve if x])
def extend_to_no(self, i):
while len(self._list) < i:
self.extend(int(self._list[-1] * 1.5))
def primerange(self, a, b):
a = max(2, a)
if a >= b: return
self.extend(b)
i = self.search(a)[1]
maxi = len(self._list) + 1
while i < maxi:
p = self._list[i - 1]
if p < b:
yield p
i += 1
else: return
def search(self, n):
if n < 2: raise ValueError
if n > self._list[-1]: self.extend(n)
b = bisect(self._list, n)
if self._list[b - 1] == n: return b, b
else: return b, b + 1
def __contains__(self, n):
if n < 2: raise ValueError
if not n % 2: return n == 2
a, b = self.search(n)
return a == b
def __getitem__(self, n):
if isinstance(n, slice):
if n.stop:
self.extend_to_no(n.stop + 1)
return self._list[n.start: n.stop: n.step]
return islice(self, n.start, n.stop, n.step)
else:
self.extend_to_no(n + 1)
return self._list[n]
sieve = Sieve()
def isprime(n):
if n <= sieve._list[-1]:
return n in sieve
for i in sieve:
if not n % i: return False
if n < i * i: return True
prime = sieve.__getitem__
primerange = lambda a, b = 0: sieve.primerange(a, b) if b else sieve.primerange(2, a)
def factorint(n):
factors = []
for i in sieve:
if n < i * i: break
while not n % i:
factors.append(i)
n //= i
if n != 1: factors.append(n)
return factors
factordict = lambda n: Counter(factorint(n))
# endregion
# region main
if __name__ == "__main__":
main()
# endregion
# endregion
```
| 89,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Tags: binary search, geometry, math, ternary search
Correct Solution:
```
import sys
import math
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
from sys import stdin, stdout
for _ in range(int(stdin.readline())):
n = int(stdin.readline())
print(1 / math.tan(math.pi / (2 * n)))
```
| 89,440 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Tags: binary search, geometry, math, ternary search
Correct Solution:
```
from math import radians,tan
t = int(input())
for _ in range(t):
n = int(input())
alpha = radians(90/n)
h = 0.5/(tan(alpha))
print(2*h)
```
| 89,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Tags: binary search, geometry, math, ternary search
Correct Solution:
```
import sys
import math
pi=math.pi
q=int(input())
for i in range(q):
a=int(sys.stdin.readline())
if a//2%2==0:
n1=a//2+1
else:
n1=a//2
n2=(a-n1)
rad=1/(2*math.sin(pi/(2*a)))
b=pow(2*rad*rad-2*rad*rad*math.cos(2*pi/(2*a)*n1),1/2)/pow(2,1/2)
c=pow(2*rad*rad-2*rad*rad*math.cos(2*pi/(2*a)*n2),1/2)/pow(2,1/2)
print(b+c)
'''
1/(2*math.sin(pi/(2*a)))
print( )
print(1/math.tan(pi/(2*a)))
'''
```
| 89,442 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Tags: binary search, geometry, math, ternary search
Correct Solution:
```
from sys import stdin, stdout
import math
def main():
# t = 1
t = int(input())
for i in range(t):
n = int(input())
n *= 2
a = 1
big_r = a / (2 * math.tan(math.pi / n))
print(big_r * 2)
main()
```
| 89,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Tags: binary search, geometry, math, ternary search
Correct Solution:
```
from math import sin, pi, sqrt
test=int(input())
answer=[]
for test_case in range(test):
n=2*int(input())
sine=sin(pi/180* (180-360/n)/2)
answer.append( str(sine/sqrt(1-sine**2)) )
print(("\n").join(answer))
```
| 89,444 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Tags: binary search, geometry, math, ternary search
Correct Solution:
```
import math
t = int(input())
for i in range(t):
n = int(input()) * 2
rad = 1 / math.sqrt(2 * (1 - math.cos(2 * math.pi / n)));
area = 0.5 * math.sin(2 * math.pi / n) * rad * rad
h = 2 * area
print(2 * h)
```
| 89,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Tags: binary search, geometry, math, ternary search
Correct Solution:
```
from decimal import Decimal
import math
for ii in range(int(input())):
n = int(input())
print(1/(math.tan(math.pi/(2*n))))
```
| 89,446 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Submitted Solution:
```
import math
t = int(input())
for i in range(t):
n = int(input())
n *= 2
ans = math.cos(math.pi / n)/math.sin(math.pi/n)
print(ans)
```
Yes
| 89,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Submitted Solution:
```
# Anuneet Anand
import math
T = int(input())
while T:
n = int(input())
m = 2*n
a = 180/(m)
x = 1/math.tan(math.radians(a))
print(x)
T = T - 1
```
Yes
| 89,448 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Submitted Solution:
```
t = int(input())
import math
for _ in range(t):
s = float(input())
a = math.pi/(2.0*s)
p = min(1/math.tan(a), 1/math.sin(a))
print(p)
```
Yes
| 89,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Submitted Solution:
```
import math
def rn():
a = int(input())
return a
def rl():
a = list(map(int, input().split()))
return a
for _ in range(int(input())):
n = rn()
n = 2*n
ang1 = math.pi/n
hyp = 1/(2*math.sin(ang1))
base = 1/2
perp = math.sqrt(hyp**2-base**2)
print(2*perp)
```
Yes
| 89,450 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Submitted Solution:
```
import math
for _ in range(int(input())):
n = int(input())
if n == 2:
print(1)
elif n == 4:
print(2.414213562)
else:
r = 1/(2*math.sin(math.radians(180/(2*n))))
print(r*2)
```
No
| 89,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Submitted Solution:
```
import sys, math,os
from io import BytesIO, IOBase
from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7
def main():
for t in range(int(data())):
n=int(data())
if n%2==0:
print(1/math.tan(((90/n)*math.pi)/180))
else:
print(1/math.cos(((90/n)*math.pi)/180))
if __name__ == '__main__':
main()
```
No
| 89,452 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Submitted Solution:
```
import math
for _ in range(int(input())):
n=int(input())
p=math.pi
r=0.5/(math.sin(p/(2*n)))
an1=n//2*(p/n)
an2=p-an1
print(r,an1,an2)
b=(r*math.sin(an1/2))*(2**0.5)
c=(r*math.sin(an2/2))*(2**0.5)
print(b+c)
```
No
| 89,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.
Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.
You can rotate 2n-gon and/or the square.
Input
The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.
Next T lines contain descriptions of test cases — one per line. Each line contains single even integer n (2 ≤ n ≤ 200). Don't forget you need to embed 2n-gon, not an n-gon.
Output
Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.
Example
Input
3
2
4
200
Output
1.000000000
2.414213562
127.321336469
Submitted Solution:
```
import math
for _ in range(int(input())):
n = 2*int(input())
#print(1+2*((n-4)/4)*(math.sin(((n-2)*(math.pi)/n)-(math.pi/2))))
print(1/(math.sin(math.pi/(n))))
```
No
| 89,454 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Tags: math
Correct Solution:
```
t = int(input())
for cases in range(t):
x, y, n = [int(i) for i in input().split()]
if n % x == y:
print(n)
else:
if y - (n % x) < 0:
k = n + y - (n % x)
else:
k = (n + y - (n % x)) - x
if k >= 0:
print(k)
else:
print(0)
```
| 89,455 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Tags: math
Correct Solution:
```
from math import *
from itertools import *
from collections import *
def ii():
return int(input())
def mas():
return [int(i) for i in input().split()]
def mapis():
return map(int, input().split())
INF = 1e9 + 1
def solve():
x, y, n = mapis()
k = (n // x) * x
if k + y > n:
print(k - x + y)
else:
print(k + y)
def main():
# t = 1
t = ii()
while t:
solve()
t -= 1
main()
```
| 89,456 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Tags: math
Correct Solution:
```
t=int(input())
for i in range(t):
x,y,n=map(int,input().split())
n-=y
n=n//x
n*=x
n+=y
print(n)
```
| 89,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Tags: math
Correct Solution:
```
t = int(input())
for test in range(t):
x,y,n = [int(x) for x in input().split()]
z = n%x
req = y-z
if req<=0:
ans = n-abs(req)
else:
ans = n-x+abs(req)
print(ans)
```
| 89,458 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Tags: math
Correct Solution:
```
n=int(input())
for _ in range(n):
x,y,n=map(int,input().split())
a=n%x
if(a-y>=0):
n=n-(a-y)
else:
n=n-a-x+y
print(n)
```
| 89,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Tags: math
Correct Solution:
```
n = int(input())
results = []
for _ in range(n):
x, y, n = input().split()
x = int(x)
y = int(y)
n = int(n)
r = n % x
if r == y:
results.append(n)
elif r < y:
res = (n - x) + (y - r)
results.append(res)
elif r > y:
res = n - (r - y)
results.append(res)
for r in results:
print(r)
```
| 89,460 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Tags: math
Correct Solution:
```
for _ in range(int(input())):
x,y,n=map(int,input().split())
f=((n-y)//x)*x + y
print(f)
```
| 89,461 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Tags: math
Correct Solution:
```
for i in range(int(input())):
x,y,n=map(int,input().split())
k=n%x
if(k==y):
print(n)
# elif(n<x):
# print(0)
else:
if(k<y):
print(n-k-(x-y))
else:
print(n-(k-y))
```
| 89,462 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Submitted Solution:
```
t=int(input())
while t>0:
t-=1
x, y, n=[int(x) for x in input().split(" ")]
v = n - n%x
while v+y > n:
v-=x
print(v+y)
```
Yes
| 89,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Submitted Solution:
```
t=int(input())
for i in range(0,t,1):
x,y,n=map(int,input().split())
s=int((n-y)/x)
sum=s*x+y
print(sum)
```
Yes
| 89,464 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Submitted Solution:
```
for _ in range(int(input())):
x, y, n = map(int, input().split())
if n % x == y:
print(n)
else:
if n % x > y:
print(n - (n % x - y))
else:
print(n - x + (y - n % x))
```
Yes
| 89,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Submitted Solution:
```
def ninja(x,y,n):
k=n%x
if k==y:
return n
elif k>y:
return n-(k-y)
else:
return n-k-(x-y)
for _ in range(int(input())):
x,y,n=map(int,input().split())
print(ninja(x,y,n))
```
Yes
| 89,466 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Submitted Solution:
```
t=int(input())
i=0
for i in range(0,t):
x, y, n = [int(x) for x in input().split()]
ans=0
j=0
if (n-n%x+y<=n):
ans=n-n%x+y
else:
ans=n-n%x+(x-y)
print(ans)
```
No
| 89,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Submitted Solution:
```
t=int(input())
for i in range(t):
x,y,n=map(int,input().split())
z=n//x
a=(z*x)+y
print(a)
```
No
| 89,468 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Submitted Solution:
```
for i in range(int(input())):
x, y, n = [int(i) for i in input().split(" ")]
temp = 0
for i in range(int(n/x)+1, 0, -1):
if i*x + y <= n:
print(i*x+y)
temp = 1
break
if temp == 0:
print(0)
```
No
| 89,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x.
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases. The next t lines contain test cases.
The only line of the test case contains three integers x, y and n (2 ≤ x ≤ 10^9;~ 0 ≤ y < x;~ y ≤ n ≤ 10^9).
It can be shown that such k always exists under the given constraints.
Output
For each test case, print the answer — maximum non-negative integer k such that 0 ≤ k ≤ n and k mod x = y. It is guaranteed that the answer always exists.
Example
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
Note
In the first test case of the example, the answer is 12339 = 7 ⋅ 1762 + 5 (thus, 12339 mod 7 = 5). It is obvious that there is no greater integer not exceeding 12345 which has the remainder 5 modulo 7.
Submitted Solution:
```
ans = []
for i in range(int(input())):
x,y,n = list(map(int,input().split()))
for k in range(n,1,-1):
if(k%x==y):
ans.append(k)
break
for a in ans:
print(a)
```
No
| 89,470 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Tags: brute force, math, number theory, sortings
Correct Solution:
```
import math as m
n = int(input())
x = list(map(int, input().split()))
x.sort()
a = m.floor(x[n-1]**(1/(n-1)))
b = 0
c = 0
for i in range(len(x)):
b += abs(x[i] - a**i)
for i in range(len(x)):
c += abs(x[i] - (a+1)**i)
print(min(c,b))
```
| 89,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Tags: brute force, math, number theory, sortings
Correct Solution:
```
import sys
import collections as cc
import random as rd
import math as mt
input = sys.stdin.readline
I = lambda : cc.deque(map(int,input().split()))
n,=I()
l=sorted(I())
if n==2:
print(l[0]-1)
sys.exit()
ans=sum(l)-n
for i in range(2,40000):
now=0
mul=1
for j in range(n):
now+=abs(mul-l[j])
if now >ans:
break
mul*=i
ans=min(now,ans)
print(ans)
```
| 89,472 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Tags: brute force, math, number theory, sortings
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
inf = 10**18
if n <= 2:
print(a[0] - 1)
else:
ans = sum(a) - n
for x in range(1, 10**9):
curPow = 1
curCost = 0
for i in range(n):
curCost += abs(a[i] - curPow)
curPow *= x
if curPow > inf:
break
if curPow > inf:
break
# if curPow / x > ans + a[n - 1]:
# break
ans = min(ans, curCost)
print(ans)
```
| 89,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Tags: brute force, math, number theory, sortings
Correct Solution:
```
n = int(input())
A = [int(i) for i in input().split()]
A = sorted(A)
m=int(pow(A[-1],1/(n-1)))
_=0
x,y=0,0
for _ in range(n):
u=pow(m,_)
x+=abs(u-A[_])
for _ in range(n):
v=pow(m+1,_)
y+=abs(v-A[_])
print(min(x,y))
```
| 89,474 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Tags: brute force, math, number theory, sortings
Correct Solution:
```
import math
n=int(input())
a=list(map(int,input().split()))
a.sort()
max_r= int(math.ceil(pow(10,9/(n-1))))
lst=[]
for r in range(1,max_r+1):
cost=0
for i in range(n):
if a[i]!=pow(r,i):
cost+= abs(pow(r,i)-a[i])
lst.append(cost)
print(min(lst))
```
| 89,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Tags: brute force, math, number theory, sortings
Correct Solution:
```
import math
def calc(a,b):
s=0
for i in range(len(a)):
s+=abs(a[i]-b**i)
return s
n=int(input())
a=list(map(int,input().split()))
a.sort()
b=int(a[-1]**(1/(n-1)))
m=calc(a,b)
for i in range(1,10000):
mt=calc(a,b+i)
if mt<=m:
m=mt
else:
break
for i in range(b,0,-1):
mt=calc(a,i)
if mt<=m:
m=mt
else:
break
print(m)
```
| 89,476 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Tags: brute force, math, number theory, sortings
Correct Solution:
```
import sys
import time
# IO region
FIO = 10
def I(): return input()
def Iint(): return int(input())
def Ilist(): return list(map(int, input().split())) # int list
def Imap(): return map(int, input().split()) # int map
def Plist(li, s=' '): print(s.join(map(str, li))) # non string list
# /IO region
en = enumerate
def answer_debug(*args):
print('\033[31m', *args, '\033[0m', file=sys.stderr)
# answer(9)
def debug(*args):
print('\033[36m', *args, '\033[0m', file=sys.stderr)
if not FIO:
if __name__ == '__main__':
main()
exit()
else:
from io import BytesIO, IOBase
import os
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# endregion
def main():
n=int(input())
l=sorted(Ilist())
# l.sort()
ans=sum(l)-n
for i in range(2,10**5):
nn=0
for j in range(n):
nn+=abs(l[j]-i**j)
# print(l[j]-i**j)
if nn>=ans:
break
if nn<ans:
ans=nn
print(ans)
if __name__ == '__main__':
main()
```
| 89,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Tags: brute force, math, number theory, sortings
Correct Solution:
```
from math import *
from collections import *
from random import *
from decimal import Decimal
from heapq import *
from bisect import *
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**5)
def lis():
return list(map(int,input().split()))
def ma():
return map(int,input().split())
def inp():
return int(input())
def st1():
return input().rstrip('\n')
t=1
def lo(n,x):
z=0
while(n):
n=n//x
z+=1
return z
while(t):
t-=1
n=inp()
a=lis()
a.sort()
co=1
ref=10**14
z=0
re=float('inf')
for i in range(1,100000):
#print(i)
if(i**n>ref):
break
z=0
co=1
#print(n)
for j in range(n):
z+=abs(co-a[j])
co=co*i
re=min(re,z)
print(re)
```
| 89,478 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Submitted Solution:
```
import os
import heapq
import sys,threading
import math
import bisect
import operator
from collections import defaultdict
#sys.setrecursionlimit(10**5)
from io import BytesIO, IOBase
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
def power(x, p):
res = 1
while p:
if p & 1:
res = (res * x)
x = (x * x)
p >>= 1
return res
def inar():
return [int(k) for k in input().split()]
def lcm(num1,num2):
return (num1*num2)//gcd(num1,num2)
def main():
#t=int(input())
t=1
for _ in range(t):
n=int(input())
arr=inar()
arr.sort()
counter=0
cost=0
take=sum(arr)
for i in range(n):
cost+=abs(arr[i]-1)
# print(cost)
if n<=32:
c=0
for i in range(1,100000):
temp=0
c=0
for j in range(n):
if power(i,j)>10**10:
c=1
break
temp+=abs(arr[j]-power(i,j))
#print(temp)
if c==0:
cost=min(cost,temp)
print(cost)
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")
if __name__ == "__main__":
main()
#threadin.Thread(target=main).start()
```
Yes
| 89,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Submitted Solution:
```
import math
n = int(input())
l = list(map(int,input().split()))
l.sort()
c1=math.ceil(l[-1]**(1/(n-1)))
c2=math.floor(l[-1]**(1/(n-1)))
dif1,dif2=0,0
for i in range(n):
dif1+=abs(c1**i-l[i])
for i in range(n):
dif2+=abs(c2**i-l[i])
print(min(dif1,dif2))
```
Yes
| 89,480 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Submitted Solution:
```
n=int(input())
arr=[int(i) for i in input().split()]
c=2
cutoff_cost=0
arr=sorted(arr)
for i in arr:
cutoff_cost+=abs(i-1)
ans=cutoff_cost
while c**(n-1) < cutoff_cost+arr[-1]:
tmpans=0
for j in range(n):
tmpans+=abs((c**j)-arr[j])
ans=min(ans,tmpans)
c+=1
print(ans)
```
Yes
| 89,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Submitted Solution:
```
n=int(input())
l = list(map(int, input().strip().split()))[:n]
l.sort()
f = sum(l) - n
cost = f
x = 2
while x**(n-1) < f + l[-1]:
currCost, p = 0, 1
for i in range(n):
currCost += abs(l[i] - p)
p*=x
cost = min(cost, currCost)
x += 1
print(cost)
```
Yes
| 89,482 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Submitted Solution:
```
import math
n=int(input())
a=list(map(int,input().split()))
a.sort()
last=a[-1]
first=a[0]
ans=9999999999999999
c1=math.ceil(math.exp(math.log(last)/(n-1)))
c2=math.ceil(math.exp(math.log(last)/(n-1)))
v1=0
v2=0
for i in range(len(a)):
v1+=abs(a[i]-c1**i)
v2+=abs(a[i]-c2**i)
print(min(v1,v2))
```
No
| 89,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Submitted Solution:
```
import sys
from math import ceil, floor
# Fast IO
def input():
a = sys.stdin.readline()
if a[-1] == "\n": a = a[:-1]
return a
def print(*argv):
n = len(argv)
for i in range(n):
if i == n-1: sys.stdout.write(str(argv[i]) + "\n")
else: sys.stdout.write(str(argv[i]) + " ")
def lcm(x, y):
from math import gcd
return (x * y) / (gcd(x, y))
def solve(n, lst):
lst = sorted(lst)
c = lst[-1] ** (1/(n-1))
if abs(ceil(c)**(n-1) - lst[-1]) <= abs(floor(c)**(n-1) - lst[-1]):
c = ceil(c)
else:
c = floor(c)
cnt = 0
for i in range(n):
cnt += abs(c**i - lst[i])
return cnt
n = int(input())
lst = list(map(int, input().split()))
print(solve(n, lst))
```
No
| 89,484 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Submitted Solution:
```
import os
import heapq
import sys,threading
import math
import operator
from collections import defaultdict,deque
from io import BytesIO, IOBase
sys.setrecursionlimit(10 ** 5)
threading.stack_size(2**27)
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def pw(a,b):
result=1
while(b>0):
if(b%2==1): result*=a
a*=a
b//=2
return result
def inpt():
return [int(k) for k in input().split()]
def main():
n=int(input())
ar=inpt()
ar.sort()
sm=sum(ar)
tp=ar[0]-1
ans=10**26
p=1
lt=10**20
if(n>100):
ans=sm-n
print(ans)
else:
p=1
ans=2*lt
while(p<10**5+1):
val=pw(p,n-1)
temp =p
if(val>lt):
print(p)
break
val=p
mx=0
for i in range(1,n):
mx+=abs(val-ar[i])
val*=temp
ans=min(ans,mx)
p+=1
print(tp+ans)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
#threading.Thread(target=main).start()
```
No
| 89,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then
* Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1.
Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5).
The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9).
Output
Print the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence.
Examples
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
Note
In the first example, we first reorder \{1, 3, 2\} into \{1, 2, 3\}, then increment a_2 to 4 with cost 1 to get a power sequence \{1, 2, 4\}.
Submitted Solution:
```
import math
from collections import deque
from sys import stdin, stdout
from string import ascii_letters
letters = ascii_letters
input = stdin.readline
#print = stdout.write
def calc(m):
bfres = 0
have = m
for i in range(1, n):
bfres += abs(have - arr[i])
have *= m
return bfres
n = int(input())
arr = sorted(map(int, input().split()))
res = arr[0] - 1
arr[0] = 1
right = int((1000000000**(1/(n - 1))))
rs = 99999999999999999
for i in range(1, right + 1):
rs = min(rs, calc(i))
print(res + rs)
```
No
| 89,486 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Tags: data structures, divide and conquer, dp, greedy, implementation
Correct Solution:
```
import sys
import math
import collections
import bisect
import itertools
import decimal
import copy
import heapq
# import numpy as np
# sys.setrecursionlimit(10 ** 6)
INF = 10 **20
# MOD = 10 ** 9 + 7
MOD = 998244353
# ni = lambda: int(sys.stdin.readline().rstrip())
# ns = lambda: map(int, sys.stdin.readline().rstrip().split())
# na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
# na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))
# flush = lambda: sys.stdout.flush()
ni = lambda: int(sys.stdin.buffer.readline())
ns = lambda: map(int, sys.stdin.buffer.readline().split())
na = lambda: list(map(int, sys.stdin.buffer.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.buffer.readline().split()))
flush = lambda: sys.stdout.flush()
# ===CODE===
def main():
t = ni()
for _ in range(t):
n, q = ns()
a = [-INF] + na() + [-INF]
ans = 0
for i in range(1, n + 1):
if a[i - 1] < a[i] and a[i] > a[i + 1]:
ans += a[i]
elif a[i - 1] > a[i] and a[i] < a[i + 1]:
ans -= a[i]
print(ans)
for _ in range(q):
l, r = ns()
for li in range(l - 2, l + 3):
if 1 <= li <= n:
if a[li - 1] < a[li] and a[li] > a[li + 1]:
ans -= a[li]
elif a[li - 1] > a[li] and a[li] < a[li + 1]:
ans += a[li]
for ri in range(max(l + 3, r - 2), r + 3):
if 1 <= ri <= n:
if a[ri - 1] < a[ri] and a[ri] > a[ri + 1]:
ans -= a[ri]
elif a[ri - 1] > a[ri] and a[ri] < a[ri + 1]:
ans += a[ri]
a[l], a[r] = a[r], a[l]
for li in range(l - 2, l + 3):
if 1 <= li <= n:
if a[li - 1] < a[li] and a[li] > a[li + 1]:
ans += a[li]
elif a[li - 1] > a[li] and a[li] < a[li + 1]:
ans -= a[li]
for ri in range(max(l + 3, r - 2), r + 3):
if 1 <= ri <= n:
if a[ri - 1] < a[ri] and a[ri] > a[ri + 1]:
ans += a[ri]
elif a[ri - 1] > a[ri] and a[ri] < a[ri + 1]:
ans -= a[ri]
print(ans)
if __name__ == '__main__':
main()
```
| 89,487 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Tags: data structures, divide and conquer, dp, greedy, implementation
Correct Solution:
```
import sys
import math
import collections
import bisect
import itertools
import decimal
import copy
import heapq
# import numpy as np
# sys.setrecursionlimit(10 ** 6)
INF = 10 **20
# MOD = 10 ** 9 + 7
MOD = 998244353
# ni = lambda: int(sys.stdin.readline().rstrip())
# ns = lambda: map(int, sys.stdin.readline().rstrip().split())
# na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
# na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))
# flush = lambda: sys.stdout.flush()
ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))
flush = lambda: sys.stdout.flush()
# ===CODE===
def main():
t = ni()
for _ in range(t):
n, q = ns()
a = [-INF] + na() + [-INF]
ans = 0
for i in range(1, n + 1):
if a[i - 1] < a[i] and a[i] > a[i + 1]:
ans += a[i]
elif a[i - 1] > a[i] and a[i] < a[i + 1]:
ans -= a[i]
print(ans)
for _ in range(q):
l, r = ns()
for li in range(l - 2, l + 3):
if 1 <= li <= n:
if a[li - 1] < a[li] and a[li] > a[li + 1]:
ans -= a[li]
elif a[li - 1] > a[li] and a[li] < a[li + 1]:
ans += a[li]
for ri in range(max(l + 3, r - 2), r + 3):
if 1 <= ri <= n:
if a[ri - 1] < a[ri] and a[ri] > a[ri + 1]:
ans -= a[ri]
elif a[ri - 1] > a[ri] and a[ri] < a[ri + 1]:
ans += a[ri]
a[l], a[r] = a[r], a[l]
for li in range(l - 2, l + 3):
if 1 <= li <= n:
if a[li - 1] < a[li] and a[li] > a[li + 1]:
ans += a[li]
elif a[li - 1] > a[li] and a[li] < a[li + 1]:
ans -= a[li]
for ri in range(max(l + 3, r - 2), r + 3):
if 1 <= ri <= n:
if a[ri - 1] < a[ri] and a[ri] > a[ri + 1]:
ans += a[ri]
elif a[ri - 1] > a[ri] and a[ri] < a[ri + 1]:
ans -= a[ri]
print(ans)
if __name__ == '__main__':
main()
```
| 89,488 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Tags: data structures, divide and conquer, dp, greedy, implementation
Correct Solution:
```
import sys
import array
input=sys.stdin.readline
t=int(input())
for _ in range(t):
n,q=map(int,input().split())
a=array.array("i",[-1]+list(map(int,input().split()))+[-1])
def f(i):
if i<=0 or i>=n+1:
return 0
if a[i-1]<a[i]>a[i+1]:
return a[i]
if a[i-1]>a[i]<a[i+1]:
return -a[i]
return 0
ans=0
for i in range(n):
ans+=f(i+1)
print(ans)
for __ in range(q):
l,r=map(int,input().split())
u,v=a[l],a[r]
ans-=f(l-1)+f(l)+f(l+1)
a[l]=v
ans+=f(l-1)+f(l)+f(l+1)
ans-=f(r-1)+f(r)+f(r+1)
a[r]=u
ans+=f(r-1)+f(r)+f(r+1)
print(ans)
```
| 89,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Tags: data structures, divide and conquer, dp, greedy, implementation
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# sys.setrecursionlimit(300000)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
data = [list(map(int,line.split())) for line in sys.stdin.readlines()]
line = 1
for _ in range(data[0][0]):
n,q = data[line]
a = [0]+data[line+1]+[0]
low,high = set(),set()
s = 0
for i in range(1,n+1):
if a[i]>a[i-1] and a[i]>a[i+1]:
high.add(a[i])
s+=a[i]
elif a[i]<a[i-1] and a[i]<a[i+1]:
low.add(a[i])
s-=a[i]
print(s)
for ii in range(line+2,line+q+2):
x,y = data[ii]
a[x],a[y] = a[y],a[x]
d = {a[x-1],a[x],a[x+1],a[y-1],a[y],a[y+1]}
t = low & d
s+=sum(t)
low-=t
t = high & d
s-=sum(t)
high-=t
d = {x-1,x,x+1,y-1,y,y+1}
for i in d:
if 0<i<=n:
if a[i]>a[i-1] and a[i]>a[i+1]:
high.add(a[i])
s+=a[i]
elif a[i]<a[i-1] and a[i]<a[i+1]:
low.add(a[i])
s-=a[i]
print(s)
line+=q+2
```
| 89,490 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Tags: data structures, divide and conquer, dp, greedy, implementation
Correct Solution:
```
from sys import stdin, stdout
input = stdin.readline
c = 0
a = []
b = []
def f(i):
if a[i] == 0:
return 0
if a[i - 1] < a[i] > a[i + 1]:
return 1
if a[i - 1] > a[i] < a[i + 1]:
return -1
return 0
def relax(i):
global c
c += (f(i) - b[i]) * a[i]
b[i] = f(i)
def relax1(i):
global c
c -= b[i] * a[i]
b[i] = 0
#print(a[i], a[i - 1] < i)
for _ in range(int(input())):
c = 0
n, q = map(int, input().split())
*a, = map(int, input().split())
a = [0] + a + [0]
b = [0] * (n + 2)
for i in range(1, n + 1):
relax(i)
print(c)
for i in range(q):
l, r = map(int, input().split())
relax1(l)
relax1(l - 1)
relax1(l + 1)
relax1(r)
relax1(r - 1)
relax1(r + 1)
a[l], a[r] = a[r], a[l]
relax(l)
relax(l - 1)
relax(l + 1)
relax(r)
relax(r - 1)
relax(r + 1)
print(c)
```
| 89,491 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Tags: data structures, divide and conquer, dp, greedy, implementation
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# sys.setrecursionlimit(300000)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
for _ in range(N()):
n,q = RL()
a = [0]+RLL()+[0]
low,high = set(),set()
s = 0
for i in range(1,n+1):
if a[i]>a[i-1] and a[i]>a[i+1]:
high.add(a[i])
s+=a[i]
elif a[i]<a[i-1] and a[i]<a[i+1]:
low.add(a[i])
s-=a[i]
print(s)
for _ in range(q):
x,y = RL()
a[x],a[y] = a[y],a[x]
t = low & {a[x-1],a[x],a[x+1],a[y-1],a[y],a[y+1]}
s+=sum(t)
low-=t
t = high & {a[x-1],a[x],a[x+1],a[y-1],a[y],a[y+1]}
s-=sum(t)
high-=t
d = {x-1,x,x+1,y-1,y,y+1}
for i in d:
if 0<i<=n:
if a[i]>a[i-1] and a[i]>a[i+1]:
high.add(a[i])
s+=a[i]
elif a[i]<a[i-1] and a[i]<a[i+1]:
low.add(a[i])
s-=a[i]
print(s)
```
| 89,492 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Tags: data structures, divide and conquer, dp, greedy, implementation
Correct Solution:
```
# Author : -pratyay-
import sys
inp=sys.stdin.buffer.readline
inar=lambda: list(map(int,inp().split()))
inin=lambda: int(inp())
inst=lambda: inp().decode().strip()
def pr(*args,end='\n'):
for _arg in args:
sys.stdout.write(str(_arg)+' ')
sys.stdout.write(end)
from math import log2
_T_=inin()
for _t_ in range(_T_):
n,q=inar()
a=[0]+inar()+[0]
diff=[]
for i in range(n+1):
diff.append(max(0,a[i+1]-a[i]))
pr(sum(diff))
ans=sum(diff)
for qq in range(q):
l,r=inar();
#print("Before: ",a,diff,ans,"l=",l,"r=",r)
al=a[l]
ar=a[r]
#after changing a[l] to ar
a[l]=ar
ans-=diff[l-1]
ans-=diff[l]
diff[l-1]=max(0,a[l]-a[l-1])
diff[l]=max(0,a[l+1]-a[l])
ans+=diff[l-1]
ans+=diff[l]
#after changing a[r] to a[l]
a[r]=al
ans-=diff[r-1]
ans-=diff[r]
diff[r-1]=max(0,a[r]-a[r-1])
diff[r]=max(0,a[r+1]-a[r])
ans+=diff[r-1]
ans+=diff[r]
#print("After: ",a,diff,ans)
pr(ans)
```
| 89,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Tags: data structures, divide and conquer, dp, greedy, implementation
Correct Solution:
```
import sys;z=sys.stdin.readline;o=[];y=lambda a,b:a-b if a-b>0 else 0
for _ in range(int(z())):
n,q=map(int,z().split());p=[0]+[*map(int,z().split())];s=m=0
for i in p:
if i>m:s+=i-m
m=i
o.append(s)
for i in range(q):
a,b=map(int,z().split())
if a==b:o.append(s);continue
va,vb=p[a],p[b];va1=p[a-1];c=b<n
if c:vb1=p[b+1]
p[a],p[b]=vb,va;lv=nv=0
if b-a<2:
if vb>va:lv+=vb-va
if va>va1:lv+=va-va1
if c and vb1>vb:lv+=vb1-vb
if va>vb:nv+=va-vb
if vb>va1:nv+=vb-va1
if c and vb1>va:nv+=vb1-va
else:
va2,vb2=p[a+1],p[b-1]
if va2>va:lv+=va2-va
if va>va1:lv+=va-va1
if vb>vb2:lv+=vb-vb2
if c and vb1>vb:lv+=vb1-vb
if va2>vb:nv+=va2-vb
if vb>va1:nv+=vb-va1
if va>vb2:nv+=va-vb2
if c and vb1>va:nv+=vb1-va
s+=nv-lv;o.append(s)
print('\n'.join(map(str,o)))
```
| 89,494 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Submitted Solution:
```
from sys import stdin
from math import log2
def readline():
return stdin.readline()
def findsum(a):
sm = 0
for i in range(len(a)):
if isMax(a, i):
sm += a[i]
elif isMin(a, i):
sm -= a[i]
return sm
def isMax(a, i):
return i != 0 and i != len(a) - 1 and a[i - 1] < a[i] > a[i + 1]
def isMin(a, i):
return i != 0 and i != len(a) - 1 and a[i - 1] > a[i] < a[i + 1]
def change(a, i1, i2, s):
used = set()
for j in [i1, i2]:
for i in range(j - 1, j + 2):
if i not in used:
if isMax(a, i):
s -= a[i]
used.add(i)
if isMin(a, i):
s += a[i]
used.add(i)
a[i1], a[i2] = a[i2], a[i1]
used = set()
for j in [i1, i2]:
for i in range(j - 1, j + 2):
if i not in used:
if isMax(a, i):
s += a[i]
used.add(i)
if isMin(a, i):
s -= a[i]
used.add(i)
return s
tests = int(readline())
for t in range(0, tests):
n, q = map(int, readline().split())
a = [0, *list(map(int, readline().rstrip("\n").split(' '))), 0]
s = findsum(a)
print(s)
for i in range(q):
i1, i2 = map(int, readline().split())
s = change(a, i1, i2, s)
print(s)
```
Yes
| 89,495 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Submitted Solution:
```
import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
n,q = list(map(int, input().split()))
arr = list(map(int, input().split()))
total = 0
last = 0
for i in range(n):
total += max(arr[i] - last, 0)
last = arr[i]
arr = [0] + arr + [arr[-1]]
print(total)
ans = []
for _ in range(q):
x,y = list(map(int, input().split()))
x_new, y_new = arr[y], arr[x]
j1, j2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)
arr[x] = x_new
arr[-1] = arr[-2]
n1, n2 = max(arr[x] - arr[x-1], 0), max(arr[x+1] - arr[x], 0)
total -= j1 + j2
total += n1 + n2
j1, j2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)
arr[y] = y_new
arr[-1] = arr[-2]
n1, n2 = max(arr[y] - arr[y-1], 0), max(arr[y+1] - arr[y], 0)
total -= j1 + j2
total += n1 + n2
ans.append(str(total))
print(*ans, sep='\n')
```
Yes
| 89,496 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
_str = str
BUFSIZE = 8192
def str(x=b''):
return x if type(x) is bytes else _str(x).encode()
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')
def inp():
return sys.stdin.readline()
def mpint():
return map(int, sys.stdin.readline().split(' '))
def itg():
return int(sys.stdin.readline())
# ############################## import
# ############################## main
def solve():
n, q = mpint()
arr = list(mpint()) + [0]
ans = 0
for i in range(n):
ans += max(0, arr[i] - arr[i - 1])
print(ans)
for _ in range(q):
lf, rg = mpint()
lf -= 1
rg -= 1
ans -= max(0, arr[rg + 1] - arr[rg])
ans -= max(0, arr[rg] - arr[rg - 1])
if rg != lf + 1:
ans -= max(0, arr[lf + 1] - arr[lf])
ans -= max(0, arr[lf] - arr[lf - 1])
arr[rg], arr[lf] = arr[lf], arr[rg]
ans += max(0, arr[rg + 1] - arr[rg])
ans += max(0, arr[rg] - arr[rg - 1])
if rg != lf + 1:
ans += max(0, arr[lf + 1] - arr[lf])
ans += max(0, arr[lf] - arr[lf - 1])
print(ans)
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
if __name__ == '__main__':
# print("YES" if solve() else "NO")
# print("yes" if solve() else "no")
# solve()
for _ in range(itg()):
# print(solve())
solve()
# Please check!
```
Yes
| 89,497 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Submitted Solution:
```
import sys
def solve(n, q, a, u):
z = []
def chk(i):
if a[i - 1] < a[i] > a[i + 1]: return a[i]
if a[i - 1] > a[i] < a[i + 1]: return -a[i]
return 0
if n == 1:
z.append(a[0])
for i in u:
z.append(a[0])
else:
a = [-1] + a + [-1]
c = 0
for i in range(1, n + 1):
c += chk(i)
z.append(c)
for l, r in u:
if l == r:
z.append(c)
else:
b = {
l, max(1, l - 1), min(n, l + 1),
r, max(1, r - 1), min(n, r + 1)
}
for j in b: c -= chk(j)
a[l], a[r] = a[r], a[l]
for j in b: c += chk(j)
z.append(c)
return z
def stdinWrapper():
while True:
yield sys.stdin.readline()
inputs = stdinWrapper()
def inputWrapper():
return next(inputs)
def getType(_type):
return _type(inputWrapper())
def getArray(_type):
return [_type(x) for x in inputWrapper().split()]
t = getType(int)
z = []
for _ in range(t):
n, q = getArray(int)
a = getArray(int)
u = [getArray(int) for _ in range(q)]
z += solve(n, q, a, u)
print('\n'.join(map(str, z)))
```
Yes
| 89,498 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.
First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.
As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.
The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....
Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.
Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.
Help Andrew and the pokémon, or team R will realize their tricky plan!
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.
The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.
i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5, and the sum of q over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.
Example
Input
3
3 1
1 3 2
1 2
2 2
1 2
1 2
1 2
7 5
1 2 5 4 3 6 7
1 2
6 7
3 4
1 2
2 3
Output
3
4
2
2
2
9
10
10
10
9
11
Note
Let's look at the third test case:
Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.
After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.
After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.
After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.
After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.
After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.
Submitted Solution:
```
import sys
def get_diff(a, pos):
return a[pos] * (int(a[pos] > a[pos + 1]) + int(a[pos] > a[pos - 1]) - 1)
def main():
iter_data = map(int, sys.stdin.read().split())
t = next(iter_data)
for t_it in range(t):
n, q = next(iter_data), next(iter_data)
a = [0] + [next(iter_data) for _ in range(n)] + [0]
all_ans = [0] * (q + 1)
diff = [0] * (n + 1)
for i in range(1, n + 1):
diff[i] = int(a[i] > a[i + 1]) + int(a[i] > a[i - 1])
cur_ans = sum(val * (diff - 1) for val, diff in zip(a, diff))
all_ans[0] = cur_ans
for q_it in range(1, q + 1):
l, r = next(iter_data), next(iter_data)
if l != r and t_it <= 300:
mod_pos = [
x for x in set((l - 1, l, l + 1, r - 1, r + 1))
if 1 <= x <= n
]
cur_ans -= sum(diff[p] * a[p] for p in mod_pos)
a[l], a[r] = a[r], a[l]
for p in mod_pos:
diff[p] = int(a[p] > a[p + 1]) + int(a[p] > a[p - 1])
cur_ans += sum(diff[p] * a[p] for p in mod_pos)
all_ans[q_it] = cur_ans
print(*all_ans, sep='\n')
if __name__ == '__main__':
main()
```
No
| 89,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.