text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Tags: constructive algorithms, implementation
Correct Solution:
```
t = int(input())
for _ in range(t):
n = input()
n = n + " "
print(n*int(n))
```
| 101,400 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Tags: constructive algorithms, implementation
Correct Solution:
```
t = int(input())
for i_t in range(t):
n = int(input())
print(*[1]*n)
```
| 101,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Tags: constructive algorithms, implementation
Correct Solution:
```
n=int(input())
for i in range(n):
a=int(input())
for j in range(a):
print(1,end=" ")
print()
```
| 101,402 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Tags: constructive algorithms, implementation
Correct Solution:
```
for _ in range(int(input())):
print(" ".join(['1' for x in range(int(input()))]))
```
| 101,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Tags: constructive algorithms, implementation
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
print('1 '*n)
```
| 101,404 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Tags: constructive algorithms, implementation
Correct Solution:
```
for i in range(int(input())):
n=int(input())
s=' '
m=[1 for z in range(n)]
m=list(map(str,m))
print(s.join(m))
```
| 101,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Tags: constructive algorithms, implementation
Correct Solution:
```
t=int(input())
for you in range(t):
n=int(input())
for i in range(n):
print(1,end=" ")
print()
```
| 101,406 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Tags: constructive algorithms, implementation
Correct Solution:
```
t = int(input())
while t:
t-=1
n = int(input())
print(n*"1 ")
```
| 101,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Submitted Solution:
```
t= int(input())
while t:
n = int(input())
arr = [1 for _ in range(n)]
print(*arr)
t-=1
```
Yes
| 101,408 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Submitted Solution:
```
for _ in range(int(input())):
a = [1 for x in range(int(input()))]
print(*a)
```
Yes
| 101,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Submitted Solution:
```
import sys
import os.path
from collections import *
import math
import bisect
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
else:
input = sys.stdin.readline
############## Code starts here ##########################
t = int(input())
while t:
t-=1
n = int(input())
for i in range(n):
print(1,end=" ")
print()
############## Code ends here ############################
```
Yes
| 101,410 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
l = [2] * n
print(*l)
```
Yes
| 101,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Submitted Solution:
```
t=int(input())
for i in range(t):
n=int(input())
l=[x for x in range(1,100)]
s=[]
if n==1:
print(24)
continue
if n==2:
print(19,33)
continue
if n==4:
print(7,37,79,49)
continue
for j in range(len(l)):
if sum(l[:j+1])%len(l[:j+1])==0 :
s.append(l[j])
if len(s)==n:
break
print(*s)
```
No
| 101,412 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Submitted Solution:
```
for _ in range(int(input())):
print('1'*int(input()))
```
No
| 101,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Submitted Solution:
```
n = int(input())
for i in range(n):
a = int(input())
ar = []
s = 1
while(a > 0):
ar.append(s)
s += 6
a -= 1
print(*ar)
```
No
| 101,414 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β 6 β is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4.
Andre calls an array a of length n perfect if the following conditions hold:
* Every nonempty subarray of this array is good.
* For every i (1 β€ i β€ n), 1 β€ a_i β€ 100.
Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first and only line of every test case contains a single integer n (1 β€ n β€ 100).
Output
For every test, output any perfect array of length n on a separate line.
Example
Input
3
1
2
4
Output
24
19 33
7 37 79 49
Note
Array [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
Submitted Solution:
```
import random
if __name__ == "__main__":
t = int(input())
while t>0:
arr = [i for i in range(1,10) if i%2==1]
arr2 = [i for i in range(1,10) if i%2==0]
n = int(input())
if n==1:
print(24)
elif n==2:
print("19 33")
elif n%2==1:
for i in range(n):
print(random.choice(arr2))
else:
for i in range(n):
print(random.choice(arr))
t-=1
```
No
| 101,415 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
import bisect
input = lambda: sys.stdin.readline().rstrip("\r\n")
for _ in range(int(input())):
n=int(input())
l=[]
r=[]
a=[]
for _ in range(n):
L,R=map(int,input().split())
l.append(L)
r.append(R)
a.append([L,R])
l.sort()
r.sort()
ans=n
for i in a:
ans=min(ans,n-bisect.bisect(l,i[1])+bisect.bisect_left(r,i[0]))
print(ans)
```
| 101,416 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
import bisect
input=sys.stdin.readline
t=int(input())
for _ in range(t):
n=int(input())
left=[]
right=[]
l=[]
for i in range(n):
p=input().split()
x=int(p[0])
y=int(p[1])
l.append((x,y))
left.append(x)
right.append(y)
left.sort()
right.sort()
mina=10**18
for i in range(n):
y=bisect.bisect_right(left,l[i][1])
y=n-y
z=bisect.bisect_left(right,l[i][0])
mina=min(mina,z+y)
print(mina)
```
| 101,417 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Tags: binary search, data structures, greedy
Correct Solution:
```
from bisect import bisect_left, bisect_right
from math import inf
from sys import stdin
def read_ints():
return map(int, stdin.readline().split())
t_n, = read_ints()
for i_t in range(t_n):
n, = read_ints()
segments = [tuple(read_ints()) for i_segment in range(n)]
ls = sorted(l for l, r in segments)
rs = sorted(r for l, r in segments)
result = +inf
for l, r in segments:
lower_n = bisect_left(rs, l)
higher_n = len(ls) - bisect_right(ls, r)
result = min(result, lower_n + higher_n)
print(result)
```
| 101,418 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
class BIT:
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
self.el = [0]*(n+1)
def sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
# assert i > 0
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
def get(self, i, j=None):
if j is None:
return self.el[i]
return self.sum(j) - self.sum(i)
# n = 6
# a = [1,2,3,4,5,6]
# bit = BIT(n)
# for i,e in enumerate(a):
# bit.add(i+1,e)
# print(bit.get(2,5)) #12 (3+4+5)
for _ in range(inp()):
n = inp()
lr = [inpl() for _ in range(n)]
s = set()
for l,r in lr:
s.add(l); s.add(r)
s = list(s); s.sort()
d = {}
for i,x in enumerate(s):
d[x] = i+1
ln = len(s)
lbit = BIT(ln+10)
rbit = BIT(ln+10)
for i,(l,r) in enumerate(lr):
lr[i][0] = d[l]; lbit.add(d[l]+1,1)
lr[i][1] = d[r]; rbit.add(d[r]+1,1)
res = INF
# print(rbit.get(1,2))
for L,R in lr:
now = rbit.get(0,L) + lbit.get(R+1,ln+10)
res = min(res,now)
print(res)
```
| 101,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Tags: binary search, data structures, greedy
Correct Solution:
```
import os,io
from bisect import bisect_left, bisect_right
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range (int(input())):
n = int(input())
l = []
r = []
a = []
for i in range (n):
li,ri = [int(i) for i in input().split()]
l.append(li)
r.append(ri)
a.append([li,ri])
l.sort()
r.sort()
cnt = n
for i in range (n):
cnt = min(cnt, n-bisect_right(l,a[i][1])+bisect_left(r,a[i][0]))
print(cnt)
```
| 101,420 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Tags: binary search, data structures, greedy
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from bisect import bisect_left, bisect_right
for _ in range (int(input())):
n = int(input())
l = []
r = []
a = []
for i in range (n):
li,ri = [int(i) for i in input().split()]
l.append(li)
r.append(ri)
a.append([li,ri])
l.sort()
r.sort()
cnt = n
for i in range (n):
cnt = min(cnt, n-bisect_right(l,a[i][1])+bisect_left(r,a[i][0]))
print(cnt)
```
| 101,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Tags: binary search, data structures, greedy
Correct Solution:
```
import bisect
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
n = int(input())
ls = []
lsl = []
lsr = []
for _ in range(n):
l, r = map(int, input().split())
ls.append([l, r])
lsl.append(l)
lsr.append(r)
lsl.sort()
lsr.sort()
cnt = n
for i in range(n):
cnt = min(cnt, n - bisect.bisect_right(lsl, ls[i][1]) + bisect.bisect_left(lsr, ls[i][0]))
print(cnt)
```
| 101,422 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Tags: binary search, data structures, greedy
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
#import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=300006, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.height=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val==0:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
elif val>=1:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
def do(self,temp):
if not temp:
return 0
ter=temp
temp.height=self.do(ter.left)+self.do(ter.right)
if temp.height==0:
temp.height+=1
return temp.height
def query(self, xor):
self.temp = self.root
cur=0
i=31
while(i>-1):
val = xor & (1 << i)
if not self.temp:
return cur
if val>=1:
self.opp = self.temp.right
if self.temp.left:
self.temp = self.temp.left
else:
return cur
else:
self.opp=self.temp.left
if self.temp.right:
self.temp = self.temp.right
else:
return cur
if self.temp.height==pow(2,i):
cur+=1<<(i)
self.temp=self.opp
i-=1
return cur
#-------------------------bin trie-------------------------------------------
def binarySearchCount1(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
for ik in range(int(input())):
n=int(input())
l=[]
l1=[]
l2=[]
for i in range(n):
a,b=map(int,input().split())
l.append((a,b))
l1.append(b)
l.sort()
l1.sort()
d=defaultdict(list)
inr = defaultdict(int)
for i in range(len(l1)):
d[l1[i]].append(i)
inr[l1[i]]+=1
w=[]
e=[0]*n
s=SegmentTree(e)
for i in range(n):
w.append(l[i][0])
w1=n
for i in range(n):
ind=binarySearchCount1(l1,len(l1),l[i][0])
if ind==n:
ans=0
else:
ind=d[l1[ind]][0]
ans=s.query(ind,n-1)
ans+=binarySearchCount(w,len(w),l[i][1])-i-1
s.__setitem__(d[l[i][1]][inr[l[i][1]]-1],1)
e[d[l[i][1]][inr[l[i][1]]-1]]=1
inr[l[i][1]]-=1
w1=min(w1,n-1-ans)
print(w1)
```
| 101,423 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Submitted Solution:
```
import sys
import math,bisect,operator
inf,mod = float('inf'),10**9+7
sys.setrecursionlimit(10 ** 5)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
I = lambda : int(sys.stdin.readline())
neo = lambda : map(int, sys.stdin.readline().split())
Neo = lambda : list(map(int, sys.stdin.readline().split()))
def overlap(v):
x,y = [],[]
for i,j in v:
x += [i]
y += [j]
x.sort()
y.sort()
Ans = 0
for i in range(n):
p,q = v[i][0],v[i][1]
r = bisect.bisect_right(x,q)
l = bisect.bisect_left(y,p)
Ans = max(Ans,r-l)
return Ans
for _ in range(I()):
n = I()
A = []
for i in range(n):
l,r = neo()
A += [(l,r)]
print(max(n-overlap(A),0))
```
Yes
| 101,424 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
for t in range(int(input())):
n=int(input())
lft=[1000000000]
rt=[0]
a=[]
for i in range(n):
l,r=map(int,input().split())
a.append([l,r])
lft.append(l)
rt.append(r)
lft.sort()
rt.sort()
count=0
mini=9999999999999
for i in range(n):
j,k,count=0,n,0
while True:
m=(j+k)//2
if(rt[m]>=a[i][0]):
k=m
else:
j=m
if(k==j+1):
break
count+=j
j,k=0,n
while True:
m=(j+k)//2
if(lft[m]>a[i][1]):
k=m
else:
j=m
if(k==j+1):
break
count+=(n-1-j)
mini=min(mini,count)
print(mini)
```
Yes
| 101,425 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Submitted Solution:
```
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
def main():
global dp
global add
for _ in range(int(stdin.readline())):
n = int(stdin.readline())
rangey = []
L = list()
R = list()
for _ in range(n):
l,r = list(map(int, stdin.readline().split()))
rangey.append([l,r])
L.append(l)
R.append(r)
L.sort()
R.sort()
mn = n + 1
for i in range(n):
l,r = rangey[i]
left = bisect_left(R, l)
right = n - bisect_right(L, r)
mn = min(left + right, mn)
stdout.write(str(mn)+"\n")
main()
```
Yes
| 101,426 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Submitted Solution:
```
"""
pppppppppppppppppppp
ppppp ppppppppppppppppppp
ppppppp ppppppppppppppppppppp
pppppppp pppppppppppppppppppppp
pppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppp
pppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp
pppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp
pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp
pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp
pppppppppppppppppppppppppppppppp
pppppppppppppppppppppp pppppppp
ppppppppppppppppppppp ppppppp
ppppppppppppppppppp ppppp
pppppppppppppppppppp
"""
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(str(var)+"\n")
def outa(*var, end="\n"): sys.stdout.write(' '.join(map(str, var)) + end)
def l(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def update(index, value):
while index <= limit:
bit[index] += value
index += index & -index
def query(index):
ret = 0
while index:
ret += bit[index]
index -= index & -index
return ret
for _ in range(int(data())):
n = int(data())
arr = [l() for _ in range(n)]
s = set()
for a, b in arr:
s.add(a)
s.add(b)
s = list(s)
s.sort()
mp = dd(int)
for i in range(len(s)):
mp[s[i]] = i + 1
for i in range(n):
arr[i] = [mp[arr[i][0]], mp[arr[i][1]]]
arr.sort()
limit = n * 2 + 10
bit = [0] * limit
limit -= 1
answer = n
for i, [a, b] in enumerate(arr):
low, high = i, n - 1
index = i
while low <= high:
mid = (low + high) >> 1
if arr[mid][0] <= b:
index = mid
low = mid + 1
else:
high = mid - 1
answer = min(answer, n - (index - i + 1 + query(n * 2 + 2) - query(a - 1)))
update(b, 1)
out(answer)
```
Yes
| 101,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Submitted Solution:
```
import sys
input=sys.stdin.readline
def update(inp,add,ar,n):
while(inp<n):
ar[inp]+=add
inp+=(inp&(-inp))
def fun1(inp,ar,n):
ans=0
while(inp):
ans+=ar[inp]
inp-=(inp&(-inp))
return ans
for _ in range(int(input())):
n=int(input())
ar=[]
se=set({})
for i in range(n):
l,r=map(int,input().split())
ar.append([l,r])
se.add(l)
se.add(r)
se=list(se)
se.sort()
dic={}
le=len(se)
for i in range(le):
dic[se[i]]=i
br=[]
for i in range(n):
br.append([dic[ar[i][0]],dic[ar[i][1]]])
br.sort(key=lambda x:x[0])
le+=1
left=[0]*(le-1)
for i in range(n):
left[br[i][0]]+=1
for i in range(1,le-1):
left[i]+=left[i-1]
right=[0]*le
ans=0
for i in range(n):
xx=left[br[i][1]]-left[br[i][0]]
yy=i-fun1(br[i][0],right,le)
ans=max(xx+yy+1,ans)
update(br[i][1]+1,1,right,le)
print(n-ans)
```
No
| 101,428 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Submitted Solution:
```
import sys
import bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def NLI(n):return [[int(i) for i in input().split()] for i in range(n)]
def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def INP():
N=9
n=random.randint(1,N)
m=random.randint(1,n*n)
A=[random.randint(1,n) for i in range(m)]
B=[random.randint(1,n) for i in range(m)]
G=[[]for i in range(n)];RG=[[]for i in range(n)]
for i in range(m):
a,b=A[i]-1,B[i]-1
if a==b:continue
G[a]+=(b,1),;RG[b]+=(a,1),
return n,m,G,RG
def Rtest(T):
case,err=0,0
for i in range(T):
inp=INP()
a1=naive(*inp)
a2=solve(*inp)
if a1==a2:
print(inp)
print('naive',a1)
print('solve',a2)
err+=1
case+=1
print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
org_inp=[];g=[[] for i in range(V)]
FromStdin=True if ls==None else False
for i in range(E):
if FromStdin:
inp=LI()
org_inp.append(inp)
else:
inp=ls[i]
if len(inp)==2:
a,b=inp;c=1
else:
a,b,c=inp
if index==1:a-=1;b-=1
aa=(a,c);bb=(b,c);g[a].append(bb)
if not Directed:g[b].append(aa)
return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
mp=[boundary]*(w+2);found={}
for i in R(h):
s=input()
for char in search:
if char in s:
found[char]=((i+1)*(w+2)+s.index(char)+1)
mp_def[char]=mp_def[replacement_of_found]
mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
mp+=[boundary]*(w+2)
return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
rt=[0]
for i in ls:rt+=[rt[-1]+i]
return rt
def bit_combination(n,base=2):
rt=[]
for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
return rt
def gcd(x,y):
if y==0:return x
if x%y==0:return y
while x%y!=0:x,y=y,x%y
return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
if show_flg:print(*inp,end=end)
mo=10**9+7
#mo=998244353
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()
show_flg=False
show_flg=True
class Comb:
def __init__(self,n):
return
def fact(self,n):
return self.fac[n]
def invf(self,n):
return self.inv[n]
def comb(self,x,y):
if y<0 or y>x:
return 0
return x*(x-1)//2
########################################################################################################################################################################
# Verified by
# https://atcoder.jp/contests/arc033/submissions/me
# https://atcoder.jp/contests/abc174/tasks/abc174_f
#
# speed up TIPS: delete update of el. non-use of getitem, setitem.
#
# Binary Indexed Tree
# Bit.add(i,x) :Add x at i-th value, the following gives the same result
# Bit[i]+=x
# Bit.sum(i) : get sum up to i-th value
# Bit.l_bound(w) get bound of index where x1+x2+...+xi<w
class Bit: # 1-indexed
def __init__(self,n,init=None):
self.size=n
self.m=len(bin(self.size))-2
self.arr=[0]*(2**self.m+1)
self.el=[0]*(2**self.m+1)
if init!=None:
for i in range(len(init)):
self.add(i,init[i])
self.el[i]=init[i]
def __str__(self):
a=[self.sum(i+1)-self.sum(i) for i in range(self.size)]
return str(a)
def add(self,i,x):
if not 0<i<=self.size:return NotImplemented
self.el[i]+=x
while i<=self.size:
self.arr[i]+=x
i+=i&(-i)
return
def sum(self,i):
if not 0<=i<=self.size:return NotImplemented
rt=0
while i>0:
rt+=self.arr[i]
i-=i&(-i)
return rt
def __getitem__(self,key):
return self.el[key]
#return self.sum(key+1)-self.sum(key)
def __setitem__(self,key,value):
self.add(key,value-self.sum(key+1)+self.sum(key))
def l_bound(self,w):
if w<=0:
return 0
x=0
k=2**self.m
while k>0:
if x+k<=self.size and self.arr[x+k]<w:
w-=self.arr[x+k]
x+=k
k>>=1
return x+1
def u_bound(self,w):
if w<=0:
return 0
x=0
k=2**self.m
while k>0:
if x+k<=self.size and self.arr[x+k]<=w:
w-=self.arr[x+k]
x+=k
k>>=1
return x+1
class Bit0(Bit): # 0-indexed
def add(self,j,x):
super().add(j+1,x)
def l_bound(self,w):
return max(super().l_bound(w)-1,0)
def u_bound(self,w):
return max(super().u_bound(w)-1,0)
class Multiset(Bit0):
def __init__(self,max_v):
super().__init__(max_v)
def insert(self,x):
super().add(x,1)
def find(self,x):
return super().l_bound(super().sum(x))
def __str__(self):
return str(self.arr)
def compress(L):
dc={v:i for i,v in enumerate(sorted(set(L)))}
return dc
ans=0
## Segment Tree ##
## Test case: ABC 146 F
## https://atcoder.jp/contests/abc146/tasks/abc146_f
## Initializer Template ##
# Range Sum: sg=SegTree(n)
# Range Minimum: sg=SegTree(n,inf,min,inf)
class SegTree:
def __init__(self,n,init_val=0,function=lambda a,b:a+b,ide=0):
self.size=n
self.ide_ele=ide
self.num=1<<(self.size-1).bit_length()
self.table=[self.ide_ele]*2*self.num
self.index=[0]*2*self.num
self.lazy=[self.ide_ele]*2*self.num
self.func=function
#set_val
if not hasattr(init_val,"__iter__"):
init_val=[init_val]*self.size
for i,val in enumerate(init_val):
self.table[i+self.num-1]=val
self.index[i+self.num-1]=i
#build
for i in range(self.num-2,-1,-1):
self.table[i]=self.func(self.table[2*i+1],self.table[2*i+2])
if self.table[i]==self.table[i*2+1]:
self.index[i]=self.index[i*2+1]
else:
self.index[i]=self.index[i*2+2]
def update(self,k,x):
k+=self.num-1
self.table[k]=x
while k:
k=(k-1)//2
res=self.func(self.table[k*2+1],self.table[k*2+2])
self.table[k]=res
## Remove if index is not needed
if res==self.table[k*2+1]:
self.index[k]=self.index[k*2+1]
else:
self.index[k]=self.index[k*2+2]
## Remove if index is not needed
def evaluate(k,l,r): #ι
ε»Άθ©δΎ‘ε¦η
if lazy[k]!=0:
node[k]+=lazy[k]
if(r-l>1):
lazy[2*k+1]+=lazy[k]//2
lazy[2*k+2]+=lazy[k]//2
lazy[k]=0
def __getitem__(self,key):
if type(key) is slice:
a=None if key.start==None else key.start
b=None if key.stop==None else key.stop
c=None if key.step==None else key.step
return self.table[self.num-1:self.num-1+self.size][slice(a,b,c)]
else:
if 0<=key<self.size:
return self.table[key+self.num-1]
elif -self.size<=key<0:
return self.table[self.size+key+self.num-1]
else:
raise IndexError("list index out of range")
def __setitem__(self,key,value):
if key>=0:
self.update(key,value)
else:
self.update(self.size+key,value)
def query(self,p,q):
if q<=p:
return self.ide_ele
p+=self.num-1
q+=self.num-2
res=self.ide_ele
while q-p>1:
if p&1==0:
res=self.func(res,self.table[p])
if q&1==1:
res=self.func(res,self.table[q])
q-=1
p=p>>1
q=(q-1)>>1
if p==q:
res=self.func(res,self.table[p])
else:
res=self.func(self.func(res,self.table[p]),self.table[q])
return res
def query_id(self,p,q):
if q<=p:
return self.ide_ele
p+=self.num-1
q+=self.num-2
res=self.ide_ele
idx=p
while q-p>1:
if p&1==0:
res=self.func(res,self.table[p])
if res==self.table[p]:
idx=self.index[p]
if q&1==1:
res=self.func(res,self.table[q])
if res==self.table[q]:
idx=self.index[q]
q-=1
p=p>>1
q=(q-1)>>1
if p==q:
res=self.func(res,self.table[p])
if res==self.table[p]:
idx=self.index[p]
else:
res=self.func(self.func(res,self.table[p]),self.table[q])
if res==self.table[p]:
idx=self.index[p]
elif res==self.table[q]:
idx=self.index[q]
return idx
def __str__(self):
# ηι
εγ葨瀺
rt=self.table[self.num-1:self.num-1+self.size]
return str(rt)
for _ in range(I()):
n=I()
p=[]
s=set()
L=[]
R=[]
for i in range(n):
l,r=LI()
p+=(l,r),
R+=r,
L+=l,
L.sort()
R.sort()
for i in range(n):
l,r=p[i]
a=bisect.bisect_left(R,l)
b=n-bisect.bisect_right(L,r)
ans=max(ans,n-1-a-b)
#show((a,b),(l,r),p,L,R)
print(n-1-ans)
```
No
| 101,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Submitted Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
a=[]
b=[]
for i in range(n):
l,r=map(int,input().split())
a.append([l,r])
b.append([l,r])
a.sort(key=lambda thing: thing[0])
b.sort(key=lambda thing: thing[1])
pointer1=0
pointer2=0
rightborder=0
ans=n-1
for i in range(n):
l=a[i][0]
r=a[i][1]
if r<=rightborder:
continue
rightborder=r
while pointer1+1<n and a[pointer1+1][0]<r:
pointer1+=1
while pointer2<n and b[pointer2][1]<l:
pointer2+=1
ans=min(ans,pointer2+n-pointer1-1)
print(ans)
```
No
| 101,430 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 β€ i β€ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good.
Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of segments. This is followed by n lines describing the segments.
Each segment is described by two integers l and r (1 β€ l β€ r β€ 10^9) β coordinates of the beginning and end of the segment, respectively.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, output a single integer β the minimum number of segments that need to be deleted in order for the set of remaining segments to become good.
Example
Input
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
Output
0
1
2
0
Submitted Solution:
```
import bisect
for _ in range(int(input())):
n=int(input())
xx=[0]*n
yy=[0]*n
arr=[(0,0)]*n
for i in range(n):
a,b=map(int,input().split())
xx[i]=a
yy[i]=b
arr[i]=(a,b)
ans=999999999
for i in range(n):
a=bisect.bisect_left(yy,arr[i][0])
b=bisect.bisect_right(xx,arr[i][1])
b=n-b
#print(a,b,arr[i])
ans=min(ans,a+b)
#print(ed)
print(ans)
```
No
| 101,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have c_1 letters 'a', c_2 letters 'b', ..., c_{26} letters 'z'. You want to build a beautiful string of length n from them (obviously, you cannot use the i-th letter more than c_i times). Each c_i is greater than n/3.
A string is called beautiful if there are no palindromic contiguous substrings of odd length greater than 1 in it. For example, the string "abacaba" is not beautiful, it has several palindromic substrings of odd length greater than 1 (for example, "aca"). Another example: the string "abcaa" is beautiful.
Calculate the number of different strings you can build, and print the answer modulo 998244353.
Input
The first line contains one integer n (3 β€ n β€ 400).
The second line contains 26 integers c_1, c_2, ..., c_{26} (n/3 < c_i β€ n).
Output
Print one integer β the number of strings you can build, taken modulo 998244353.
Examples
Input
4
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Output
422500
Input
3
2 2 2 2 2 2 3 3 3 2 2 2 2 2 2 3 3 3 2 2 3 2 2 3 2 2
Output
16900
Input
400
348 322 247 158 209 134 151 267 268 176 214 379 372 291 388 135 147 304 169 149 193 351 380 368 181 340
Output
287489790
Submitted Solution:
```
from math import fabs
s = input()
n = len(s)
cur = ans = 0
for ch in s:
ans += int(fabs(int(ch) - cur))*n
cur = int(ch)
n -= 1
print(ans)
```
No
| 101,432 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have c_1 letters 'a', c_2 letters 'b', ..., c_{26} letters 'z'. You want to build a beautiful string of length n from them (obviously, you cannot use the i-th letter more than c_i times). Each c_i is greater than n/3.
A string is called beautiful if there are no palindromic contiguous substrings of odd length greater than 1 in it. For example, the string "abacaba" is not beautiful, it has several palindromic substrings of odd length greater than 1 (for example, "aca"). Another example: the string "abcaa" is beautiful.
Calculate the number of different strings you can build, and print the answer modulo 998244353.
Input
The first line contains one integer n (3 β€ n β€ 400).
The second line contains 26 integers c_1, c_2, ..., c_{26} (n/3 < c_i β€ n).
Output
Print one integer β the number of strings you can build, taken modulo 998244353.
Examples
Input
4
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Output
422500
Input
3
2 2 2 2 2 2 3 3 3 2 2 2 2 2 2 3 3 3 2 2 3 2 2 3 2 2
Output
16900
Input
400
348 322 247 158 209 134 151 267 268 176 214 379 372 291 388 135 147 304 169 149 193 351 380 368 181 340
Output
287489790
Submitted Solution:
```
import itertools, sys
num = [1, 6, 8, 9]
perm = itertools.permutations(num)
sev = {}
for i in perm:
ans=0
for j in i:
ans*=10
ans+=j
sev[ans % 7] = ans
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
val=input().decode().strip()
nums = [0] * 10
for i in num:
nums[i] = 1
nn=""
vl=0
for i in val:
if (nums[int(i)]):
nums[int(i)] = 0
continue
vl *= 10
vl += int(i)
vl %= 7
sys.stdout.write(i)
vl *= 10**4
vl %= 7
sys.stdout.write(str(sev[(7 - vl) % 7]))
```
No
| 101,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have c_1 letters 'a', c_2 letters 'b', ..., c_{26} letters 'z'. You want to build a beautiful string of length n from them (obviously, you cannot use the i-th letter more than c_i times). Each c_i is greater than n/3.
A string is called beautiful if there are no palindromic contiguous substrings of odd length greater than 1 in it. For example, the string "abacaba" is not beautiful, it has several palindromic substrings of odd length greater than 1 (for example, "aca"). Another example: the string "abcaa" is beautiful.
Calculate the number of different strings you can build, and print the answer modulo 998244353.
Input
The first line contains one integer n (3 β€ n β€ 400).
The second line contains 26 integers c_1, c_2, ..., c_{26} (n/3 < c_i β€ n).
Output
Print one integer β the number of strings you can build, taken modulo 998244353.
Examples
Input
4
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Output
422500
Input
3
2 2 2 2 2 2 3 3 3 2 2 2 2 2 2 3 3 3 2 2 3 2 2 3 2 2
Output
16900
Input
400
348 322 247 158 209 134 151 267 268 176 214 379 372 291 388 135 147 304 169 149 193 351 380 368 181 340
Output
287489790
Submitted Solution:
```
n = int(input())
c = list(map(int, input().split()))
print(26*26*(25**(n-2)) % 998244353)
#print(26*26*25*25)
'''
ΠΡΠ΅Π³ΠΎ Π²Π°ΡΠΈΠ°Π½ΡΠΎΠ²: 26^n
AXA
n ans
1 26
2 26*26
3 26*26*25
4 **** 26*26 25*25*25*25*25
[2, 2, 2, 2, 2, 2, 2, 2...]
1. C_26_n
2. C_26_(n - 1) * n - 1
3.
'''
```
No
| 101,434 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have c_1 letters 'a', c_2 letters 'b', ..., c_{26} letters 'z'. You want to build a beautiful string of length n from them (obviously, you cannot use the i-th letter more than c_i times). Each c_i is greater than n/3.
A string is called beautiful if there are no palindromic contiguous substrings of odd length greater than 1 in it. For example, the string "abacaba" is not beautiful, it has several palindromic substrings of odd length greater than 1 (for example, "aca"). Another example: the string "abcaa" is beautiful.
Calculate the number of different strings you can build, and print the answer modulo 998244353.
Input
The first line contains one integer n (3 β€ n β€ 400).
The second line contains 26 integers c_1, c_2, ..., c_{26} (n/3 < c_i β€ n).
Output
Print one integer β the number of strings you can build, taken modulo 998244353.
Examples
Input
4
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Output
422500
Input
3
2 2 2 2 2 2 3 3 3 2 2 2 2 2 2 3 3 3 2 2 3 2 2 3 2 2
Output
16900
Input
400
348 322 247 158 209 134 151 267 268 176 214 379 372 291 388 135 147 304 169 149 193 351 380 368 181 340
Output
287489790
Submitted Solution:
```
# Python3 program to replace c1 with c2
# and c2 with c1
def replace(s, c1, c2):
l = len(s)
# loop to traverse in the string
for i in range(l):
# check for c1 and replace
if (s[i] == c1):
s = s[0:i] + c2 + s[i + 1:]
# check for c2 and replace
elif (s[i] == c2):
s = s[0:i] + c1 + s[i + 1:]
return s
# Driver Code
if __name__ == '__main__':
s = "grrksfoegrrks"
c1 = 'e'
c2 = 'r'
print(replace(s, c1, c2))
# This code is contributed
# by PrinciRaj1992
```
No
| 101,435 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Tags: brute force, constructive algorithms, graphs, greedy, strings
Correct Solution:
```
from __future__ import division, print_function
import math
import sys
import os
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input().strip()
return(list(s[:len(s)]))
def invr():
return(map(int,input().split()))
alp=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
n,k=invr()
l1=[]
for i in range(k):
for j in range(i,k):
if i==j:
l1.append(alp[i])
continue
l1.append(alp[i]+alp[j])
s="".join(l1)
v=n//k + 1
ans=s*v
print(ans[:n])
```
| 101,436 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Tags: brute force, constructive algorithms, graphs, greedy, strings
Correct Solution:
```
n,k=map(int,input().split())
ans=''
for i in range(k):
temp=chr(ord('a')+i)
ans+=temp
for j in range(i+1,k):
ans+=temp+chr(ord('a')+j)
if len(ans)<n:
while(len(ans)<n):
ans+=ans
print(ans[:n])
```
| 101,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Tags: brute force, constructive algorithms, graphs, greedy, strings
Correct Solution:
```
import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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
self.BUFSIZE = 8192
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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 = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def get_int():
return int(input())
def get_ints():
return list(map(int, input().split(' ')))
def get_int_grid(n):
return [get_ints() for _ in range(n)]
def get_str():
return input().strip()
def get_strs():
return get_str().split(' ')
def flat_list(arr):
return [item for subarr in arr for item in subarr]
def yes_no(b):
if b:
return "YES"
else:
return "NO"
def binary_search(good, left, right, delta=1, right_true=False):
"""
Performs binary search
----------
Parameters
----------
:param good: Function used to perform the binary search
:param left: Starting value of left limit
:param right: Starting value of the right limit
:param delta: Margin of error, defaults value of 1 for integer binary search
:param right_true: Boolean, for whether the right limit is the true invariant
:return: Returns the most extremal value interval [left, right] which is good function evaluates to True,
alternatively returns False if no such value found
"""
limits = [left, right]
while limits[1] - limits[0] > delta:
if delta == 1:
mid = sum(limits) // 2
else:
mid = sum(limits) / 2
if good(mid):
limits[int(right_true)] = mid
else:
limits[int(~right_true)] = mid
if good(limits[int(right_true)]):
return limits[int(right_true)]
else:
return False
def prefix_sums(a):
p = [0]
for x in a:
p.append(p[-1] + x)
return p
def solve_a():
n = get_int()
r = get_ints()
return r.count(1) + r.count(3)
def solve_b():
a, b, c = get_ints()
swap = False
if b > a:
swap = True
a, b = b, a
x = 10 ** (a - 1)
y = int('1' * (b - c + 1) + '0' * (c - 1))
if swap:
return y, x
else:
return x, y
def solve_c():
n, q = get_ints()
a = get_ints()
a_max = max(a)
t = get_ints()
firsts = [-1 for _ in range(a_max)]
for i, v in enumerate(a):
if firsts[v - 1] == -1:
firsts[v - 1] = i
ans = []
for q in t:
q -= 1
tmp = firsts[q]
firsts[q] = 0
ans.append(tmp + 1)
for i, x in enumerate(firsts):
if i != q and firsts[i] < tmp:
firsts[i] += 1
return ans
def solve_d():
n, k = get_ints()
path = [0]
G = {j: [i for i in range(k)] for j in range(k)}
while len(path) < (k * k):
curr = path[-1]
foll = G[curr].pop()
path.append(foll)
ans = path * (n // len(path)) + path[:n % (len(path))]
alpha = list(string.ascii_lowercase)
ans_alpha = [alpha[x] for x in ans]
return ''.join(ans_alpha)
print(solve_d())
```
| 101,438 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Tags: brute force, constructive algorithms, graphs, greedy, strings
Correct Solution:
```
n,k=map(int,input().split())
out=[]
for i in range(k):
out.append(chr(97+i))
for j in range(i+1,k):
out.append(chr(97+i))
out.append(chr(97+j))
while len(out)<n:
out+=out
print("".join(out[:n]))
```
| 101,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Tags: brute force, constructive algorithms, graphs, greedy, strings
Correct Solution:
```
n, k = [int(s) for s in input().split(" ")]
s = ""
for i in range(k):
s += chr(i+97)
for j in range(i+1, k):
s += chr(i+97) + chr(j+97)
while len(s) < n:
s *= 2
print(s[:n])
```
| 101,440 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Tags: brute force, constructive algorithms, graphs, greedy, strings
Correct Solution:
```
import sys,heapq,math
from collections import defaultdict
input=sys.stdin.readline
n,k=map(int,input().split())
countarr=[[0 for _ in range(k)] for _ in range(k)]
res=['a'] #'a'->97
for i in range(1,n):
row=ord(res[-1])-97
mini=float('inf')
col=-1
for j in range(k):
if(countarr[row][j]<=mini):
mini=countarr[row][j]
col=j
res.append(chr(97+col))
countarr[row][col]+=1
print("".join(res))
```
| 101,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Tags: brute force, constructive algorithms, graphs, greedy, strings
Correct Solution:
```
n, k = map(int,input().split())
s = 'abcdefghijklmnopqrstuvwxyz'
s = s[:k]
dic = {}
#for c1 in s:
# for c2 in s:
# dic[c1+c2] = 0
ans = ""
for i in range(k):
ans += chr(97+i)
for j in range(i+1,k):
ans += chr(97+i) + chr(97+j)
m = len(ans)
ans = ans*(n//m) + ans[:n%m]
print(ans)
```
| 101,442 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Tags: brute force, constructive algorithms, graphs, greedy, strings
Correct Solution:
```
a = list('abcdefghijklmnopqrstuvwxyz')
n, k = map(int, input().split())
if k >= n:
print(*a[0:n], sep = '')
else:
ans = ''
for i in range(k):
ans += a[i]
for j in range(i + 1, k): ans += a[i] + a[j]
while n > len(ans): ans *= 2
print(ans[0:n])
```
| 101,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Submitted Solution:
```
import sys
ints = (int(x) for x in sys.stdin.read().split())
sys.setrecursionlimit(3000)
def magic(N=26):
ans = [None]*(N+1)
ans[1] = [(0,0)]
for k in range(2, N+1):
f = [(0,k-1), (k-1,k-1), (k-1,0)]
for i,j in ans[k-1]:
if i==j!=0:
f.append((i, k-1))
f.append((k-1, j))
f.append((i,j))
ans[k] = f
return ans
def main():
n, k = (next(ints) for i in range(2))
f = [i for i,j in magic(k)[k]]
#print(f)
f = ''.join(chr(97+f[i]) for i in range(len(f)))
ans = (f * (1+(n//len(f))))[:n]
assert len(ans)==n
print(ans)
return
main()
```
Yes
| 101,444 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Submitted Solution:
```
import random
import sys
def input():
return sys.stdin.readline().rstrip()
def slv(n, k):
"""
I feel really sad I could not solve this in time...
However,It's really worthful that I could recognize I'm not good at construction!s
"""
def construct(K):
if K == 1:
return [1, 1]
else:
tmp = [1, K]
for j in range(K - 1, 1, -1):
tmp.append(K)
tmp.append(j)
tmp.append(K)
return tmp + construct(K - 1)
tmpans = construct(k)[:-1] * (n//(k * k) + 10)
assert all(v <= k for v in tmpans)
ans = list(map(lambda x: chr(x + ord('a') - 1), tmpans))[:n]
print("".join(ans))
return
def main():
n, k = map(int, input().split())
slv(n, k)
return
if __name__ == "__main__":
main()
```
Yes
| 101,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Submitted Solution:
```
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
#import io,os; input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #for pypy
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
from random import shuffle
n,k = ip()
x = 'abcdefghijklmnopqrstuvwxyz'[:k]
st = []
for i in range(k):
st.append(x[i])
for j in range(i+1,k):
st.append(x[i])
st.append(x[j])
s = ''.join(st)
while len(s) < n:
s += s
print(s[:n])
```
Yes
| 101,446 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Submitted Solution:
```
n, k = map(int, input().split())
ans = 'a'
cycle = 1
tmp = ''
if k==1:
print('a'*n)
elif k==2:
tmp = 'aabba'
if n<=5:
print(tmp[:n])
else:
ans = tmp
n -= 5
while n>=4:
ans += tmp[1:]
n -= 4
if n>0:
ans += tmp[1:1+n]
print(ans)
else:
tmp = 'aabba'
cnt = 3
while cnt<=k:
cnt2 = 2
while cnt2<=cnt:
tmp += chr(cnt-1+ord('a'))
tmp += chr(cnt2-1+ord('a'))
cnt2 += 1
tmp += 'a'
cnt += 1
if n<=len(tmp):
print(tmp[:n])
else:
ans = tmp
n -= len(tmp)
while n>=len(tmp)-1:
ans += tmp[1:]
n -= len(tmp)-1
if n>0:
ans += tmp[1:1+n]
print(ans)
```
Yes
| 101,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M = 10**9 + 7
EPS = 1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
for _ in range(1):
n,k = value()
s = input()
have = defaultdict(set)
ans = []
for i in range(k):
ans.extend([ALPHA[i]]*2)
have[ans[-1]].add(ans[-1])
if(i+1<k): have[ans[-1]].add(ALPHA[i+1])
# print(ans)
while(len(ans) < n):
got = False
for i in ALPHA[:k]:
if(i not in have[ans[-1]]):
have[ans[-1]].add(i)
ans.append(i)
got = True
if(not got): break
ans = ans + ans[::-1]
need = Ceil(n,len(ans))
ans = ans * need
print(*ans[:n],sep = "")
```
No
| 101,448 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Submitted Solution:
```
# cook your dish here
from collections import defaultdict,OrderedDict,Counter
from sys import stdin,stdout
from bisect import bisect_left,bisect_right
# import numpy as np
from queue import Queue,PriorityQueue
from heapq import *
from statistics import *
from math import *
import fractions
import copy
from copy import deepcopy
import sys
import io
sys.setrecursionlimit(10000)
import math
import os
import bisect
import collections
mod=int(pow(10,9))+7
import random
from random import *
from time import time;
def ncr(n, r, p=mod):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def normalncr(n,r):
r=min(r,n-r)
count=1;
for i in range(n-r,n+1):
count*=i;
for i in range(1,r+1):
count//=i;
return count
inf=float("inf")
adj=defaultdict(set)
visited=defaultdict(int)
def addedge(a,b):
adj[a].add(b)
adj[b].add(a)
def bfs(v):
q=Queue()
q.put(v)
visited[v]=1
while q.qsize()>0:
s=q.get_nowait()
print(s)
for i in adj[s]:
if visited[i]==0:
q.put(i)
visited[i]=1
def dfs(v,visited):
if visited[v]==1:
return;
visited[v]=1
print(v)
for i in adj[v]:
dfs(i,visited)
# a9=pow(10,6)+10
# prime = [True for i in range(a9 + 1)]
# def SieveOfEratosthenes(n):
# p = 2
# while (p * p <= n):
# if (prime[p] == True):
# for i in range(p * p, n + 1, p):
# prime[i] = False
# p += 1
# SieveOfEratosthenes(a9)
# prime_number=[]
# for i in range(2,a9):
# if prime[i]:
# prime_number.append(i)
def reverse_bisect_right(a, x, lo=0, hi=None):
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x > a[mid]:
hi = mid
else:
lo = mid+1
return lo
def reverse_bisect_left(a, x, lo=0, hi=None):
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x >= a[mid]:
hi = mid
else:
lo = mid+1
return lo
def get_list():
return list(map(int,input().split()))
def get_str_list_in_int():
return [int(i) for i in list(input())]
def get_str_list():
return list(input())
def get_map():
return map(int,input().split())
def input_int():
return int(input())
def matrix(a,b):
return [[0 for i in range(b)] for j in range(a)]
def swap(a,b):
return b,a
def find_gcd(l):
a=l[0]
for i in range(len(l)):
a=gcd(a,l[i])
return a;
def is_prime(n):
sqrta=int(sqrt(n))
for i in range(2,sqrta+1):
if n%i==0:
return 0;
return 1;
def prime_factors(n):
while n % 2 == 0:
return [2]+prime_factors(n//2)
sqrta = int(sqrt(n))
for i in range(3,sqrta+1,2):
if n%i==0:
return [i]+prime_factors(n//i)
return [n]
def p(a):
if type(a)==str:
print(a+"\n")
else:
print(str(a)+"\n")
def ps(a):
if type(a)==str:
print(a)
else:
print(str(a))
def kth_no_not_div_by_n(n,k):
return k+(k-1)//(n-1)
def forward_array(l):
n=len(l)
stack = []
forward=[0]*n
for i in range(len(l) - 1, -1, -1):
while len(stack) and l[stack[-1]] < l[i]:
stack.pop()
if len(stack) == 0:
forward[i] = len(l);
else:
forward[i] = stack[-1]
stack.append(i)
return forward;
def backward_array(l):
n=len(l)
stack = []
backward=[0]*n
for i in range(len(l)):
while len(stack) and l[stack[-1]] < l[i]:
stack.pop()
if len(stack) == 0:
backward[i] = -1;
else:
backward[i] = stack[-1]
stack.append(i)
return backward
nc="NO"
yc="YES"
ns="No"
ys="Yes"
# import math as mt
# MAXN=10**7
# spf = [0 for i in range(MAXN)]
# def sieve():
# spf[1] = 1
# for i in range(2, MAXN):
# # marking smallest prime factor
# # for every number to be itself.
# spf[i] = i
#
# # separately marking spf for
# # every even number as 2
# for i in range(4, MAXN, 2):
# spf[i] = 2
#
# for i in range(3, mt.ceil(mt.sqrt(MAXN))):
#
# # checking if i is prime
# if (spf[i] == i):
#
# # marking SPF for all numbers
# # divisible by i
# for j in range(i * i, MAXN, i):
#
# # marking spf[j] if it is
# # not previously marked
# if (spf[j] == j):
# spf[j] = i
# def getFactorization(x):
# ret = list()
# while (x != 1):
# ret.append(spf[x])
# x = x // spf[x]
#
# return ret
# sieve()
# if(os.path.exists('input.txt')):
# sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# input=stdin.readline
# print=stdout.write
def char(a):
return chr(a+97)
for i in range(1):
n,k=get_map()
# a=[chr(i+97) for i in range(k)]
# b=a[::-1]
# c=a[::2]+a[1::2]
# d=b[::2]+b[1::2]
# arr=[]
# gamma=[]
# for i in range(ceil(n/k)):
# if(i%4==0):
# gamma+=a;
# elif i%4==1:
# gamma+=b;
# elif i%4==2:
# gamma+=c;
# elif i%4==3:
# gamma+=d
# print("".join(gamma[:n]))
arr=[]
if k==1:
print('a'*n)
continue
for i in range(k):
for j in range(i+1,k):
arr.append(char(i))
arr.append(char(j))
arr+=arr[::-1]
while len(arr)<n:
arr+=arr
print("".join(arr[:n]))
```
No
| 101,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
# import threading
from math import inf, log2
from collections import defaultdict
# threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#----------------------------------------------------------------------------------------------------------------
class LazySegmentTree:
def __init__(self, array, func=max):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1
self.func = func
self.default = 0 if self.func != min else inf
self.data = [self.default] * (2 * self.size)
self.lazy = [0] * (2 * self.size)
self.process(array)
def process(self, array):
self.data[self.size : self.size+self.n] = array
for i in range(self.size-1, -1, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i+1])
def push(self, index):
"""Push the information of the root to it's children!"""
self.lazy[2*index] += self.lazy[index]
self.lazy[2*index+1] += self.lazy[index]
self.data[2 * index] += self.lazy[index]
self.data[2 * index + 1] += self.lazy[index]
self.lazy[index] = 0
def build(self, index):
"""Build data with the new changes!"""
index >>= 1
while index:
self.data[index] = self.func(self.data[2*index], self.data[2*index+1]) + self.lazy[index]
index >>= 1
def query(self, alpha, omega):
"""Returns the result of function over the range (inclusive)!"""
res = self.default
alpha += self.size
omega += self.size + 1
for i in range(len(bin(alpha)[2:])-1, 0, -1):
self.push(alpha >> i)
for i in range(len(bin(omega-1)[2:])-1, 0, -1):
self.push((omega-1) >> i)
while alpha < omega:
if alpha & 1:
res = self.func(res, self.data[alpha])
alpha += 1
if omega & 1:
omega -= 1
res = self.func(res, self.data[omega])
alpha >>= 1
omega >>= 1
return res
def update(self, alpha, omega, value):
"""Increases all elements in the range (inclusive) by given value!"""
alpha += self.size
omega += self.size + 1
l, r = alpha, omega
while alpha < omega:
if alpha & 1:
self.data[alpha] += value
self.lazy[alpha] += value
alpha += 1
if omega & 1:
omega -= 1
self.data[omega] += value
self.lazy[omega] += value
alpha >>= 1
omega >>= 1
self.build(l)
self.build(r-1)
#---------------------------------------------------------------------------------------------
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count = 0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
k = 1 << 32
for i in range(31, -1, -1):
k //= 2
val = pre_xor & k
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count += 1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, p):
ans = 0
self.temp = self.root
k = 1 << 32
for i in range(31, -1, -1):
k //= 2
val = p & k
if val == 0:
if self.temp.right and self.temp.right.count > 0:
self.temp = self.temp.right
ans ^= k
else:
self.temp = self.temp.left
else:
if self.temp.left and self.temp.left.count > 0:
self.temp = self.temp.left
ans ^= k
else:
self.temp = self.temp.right
return ans
# -------------------------bin trie-------------------------------------------
for ik in range(1):
n,k=map(int,input().split())
if k==1:
print('a'*n)
continue
s=[]
c=n
ap=[]
for i in range(k):
ap.append(chr(i+97))
for i in range(k):
for j in range(i+1,k):
s.append(ap[i]+ap[j])
for j in range(i):
s.append(ap[i]+ap[j])
i=0
ans=""
while(c>1):
ans+=s[i%len(s)]
c-=2
i+=1
if c==1:
ans+=s[i%len(s)][0]
print(ans)
```
No
| 101,450 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the cost of a string s as the number of index pairs i and j (1 β€ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
Input
The only line contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Submitted Solution:
```
from sys import stdin,stdout
stdin.readline
def mp(): return list(map(int, stdin.readline().strip().split()))
def it():return int(stdin.readline().strip())
from collections import defaultdict as dd,Counter as C,deque
from math import ceil,gcd,sqrt,factorial
n,k=mp()
v=[]
x = n%k
n = n-x
while n:
for i in range(k):
v.append(str(chr(i+97)))
n -= k
for i in range(x):
v.append(str(chr(i+97)))
print(''.join(v))
```
No
| 101,451 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Tags: dp, implementation, strings
Correct Solution:
```
n, q = map(int, input().split())
s = input()
ps = [0 for i in range(n+1)]
for i in range(n):
ps[i+1] += ps[i]+ord(s[i]) % 96
for _ in range(q):
l, r = map(int, input().split())
print(ps[r]-ps[l-1])
```
| 101,452 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Tags: dp, implementation, strings
Correct Solution:
```
n,q=[int(x) for x in input().split()]
l=input()
s=[]
s.append(ord(l[0])-96)
for i in range(1,n):
s.append(s[i-1]+ord(l[i])-96)
while q:
a,b=[int(x) for x in input().split()]
if a!=1:
print(s[b-1]-s[a-2])
else:
print(s[b-1])
q-=1
```
| 101,453 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Tags: dp, implementation, strings
Correct Solution:
```
import sys
import math
import random
from queue import PriorityQueue as PQ
from bisect import bisect_left as BSL
from bisect import bisect_right as BSR
from collections import OrderedDict as OD
from collections import Counter
from itertools import permutations
from decimal import Decimal as BIGFLOAT
from copy import deepcopy
# mod = 998244353
mod = 1000000007
MOD = mod
sys.setrecursionlimit(1000000)
try:
sys.stdin = open("actext.txt", "r")
OPENFILE = 1
except:
pass
def get_ints():
return map(int,input().split())
def palindrome(s):
mid = len(s)//2
for i in range(mid):
if(s[i]!=s[len(s)-i-1]):
return False
return True
def check(i,n):
if(0<=i<n):
return True
else:
return False
# -----------------------------------------------------------------------------------------
n,q= get_ints()
s = input()
mp = {}
for num,i in enumerate('abcdefghijklmnopqrstuvwxyz'):
mp[i] = num+1
# print(mp)
# count = 0
# for i in s:
# if(i not in mp):
# count+=1
# mp[i] = count
arr = []
for i in s:
arr.append(mp[i])
pre = [0]
for i in arr:
pre.append(pre[-1]+i)
for qq in range(q):
l,r = get_ints()
print(pre[r]-pre[l-1])
```
| 101,454 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Tags: dp, implementation, strings
Correct Solution:
```
from string import ascii_lowercase as asc
alphabet = {asc[i]:i+1 for i in range(len(asc))}
n,q = [int(x) for x in input().split()]
stroke = input()
sums = []
for i in stroke:
sums.append(sums[-1]+alphabet[i] if sums != [] else alphabet[i])
for i in range(q):
l,r = [int(x)-1 for x in input().split()]
l -= 1
if l < 0:
print(sums[r])
else:
print(sums[r]-sums[l])
```
| 101,455 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Tags: dp, implementation, strings
Correct Solution:
```
n,q=input().split()
string=str(input())
L=[]
answer=0
for i in range(len(string)):
answer+=(ord(string[i])-96)
L.append(answer)
for i in range(int(q)):
a,b=input().split()
if(int(a)==1):
print(L[int(b)-1])
else:
print(L[int(b)-1]-L[int(a)-2])
```
| 101,456 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Tags: dp, implementation, strings
Correct Solution:
```
n, t = map(int, input().split())
s = input()
arr = [0]
for x in s:
arr.append(arr[-1] + (ord(x) - ord('a') + 1))
for _ in range(t):
a, b = map(int, input().split())
print(arr[b] - arr[a - 1])
```
| 101,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Tags: dp, implementation, strings
Correct Solution:
```
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
s=input()
temp=[0]
for i in range(len(s)):
temp.append(temp[-1]+ord(s[i])-ord('a')+1)
while q>0:
q-=1
l,r=map(int,input().split())
print(temp[r]-temp[l-1])
```
| 101,458 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Tags: dp, implementation, strings
Correct Solution:
```
n,q = map(int,input().split())
s = input()
dp = []
ans = 0
for i in range(1,n+1):
dp.append(ans)
ans+=ord(s[i-1])-96
dp.append(ans)
for _ in range(q):
left,right = map(int,input().split())
print(dp[right]-dp[left-1])
```
| 101,459 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Submitted Solution:
```
n, q=map(int, input().split())
s=input()
alp={'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20, 'u':21, 'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
li=[0]
sum=0
for i in range(n):
sum+=alp[s[i]]
li.append(sum)
for i in range(q):
x, y=map(int, input().split())
print(li[y]-li[x-1])
```
Yes
| 101,460 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Submitted Solution:
```
letters = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w',
'x', 'y', 'z')
n, q = map(int, input().split())
s = input()
sums = [0]
for k in range(len(s)):
sums.append(sums[k]+letters.index(s[k])+1)
for i in range(q):
l, r = map(int, input().split())
print(sums[r]-sums[l-1])
```
Yes
| 101,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Submitted Solution:
```
def solve(l ,r):
return miku[r] - miku[l - 1]
n, q = map(int, input().split())
s = input()
miku = [0] * (n + 1)
for i in range(1, n + 1):
miku[i] += miku[i - 1] + ord(s[i - 1]) - 96
for i in range(q):
l, r = map(int, input().split())
print(solve(l, r))
```
Yes
| 101,462 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Submitted Solution:
```
from bisect import insort,bisect_right,bisect_left
from sys import stdout, stdin, setrecursionlimit
from math import sqrt,ceil,floor,factorial,gcd,log2,log10
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from string import *
from queue import *
from heapq import *
from re import *
from os import *
####################################---fast-input-output----#########################################
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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
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:
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")
stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)
graph, mod, szzz = {}, 10**9 + 7, lambda: sorted(zzz())
def getStr(): return input()
def getInt(): return int(input())
def listStr(): return list(input())
def getStrs(): return input().split()
def isInt(s): return '0' <= s[0] <= '9'
def input(): return stdin.readline().strip()
def zzz(): return [int(i) for i in input().split()]
def output(answer, end='\n'): stdout.write(str(answer) + end)
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def getPrimes(N = 10**5):
SN = int(sqrt(N))
sieve = [i for i in range(N+1)]
sieve[1] = 0
for i in sieve:
if i > SN:
break
if i == 0:
continue
for j in range(2*i, N+1, i):
sieve[j] = 0
prime = [i for i in range(N+1) if sieve[i] != 0]
return prime
def primeFactor(n,prime=getPrimes()):
lst = []
mx=int(sqrt(n))+1
for i in prime:
if i>mx:break
while n%i==0:
lst.append(i)
n//=i
if n>1:
lst.append(n)
return lst
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
#################################################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some-one , Then you probably don't know him !
--Try & again try, maybe you're just one statement away!
"""
##################################################---START-CODING---###############################################
# num = getInt()
# for _ in range(num):
# n,x,t=zzz()
# p=(t//x)
# ans = p*(n-p) + (p*(p-1)//2)
# print(ans)
n,q=zzz()
arr = getStr()
s=[]
for i in range(n):
s.append((ord(arr[i])-96))
s=[0]+list(accumulate(s))
for _ in range(q):
l,r=zzz()
print(s[r]-s[l-1])
```
Yes
| 101,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Submitted Solution:
```
def I():
return input()
def II():
return int(I())
def M():
return map(int,I().split())
def L():
return list(M())
# for _ in range(II())
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}
n,q = M()
s = I()
a = [0]*n
a[0] = d.get(s[0])
for i in range(1,n):
a[i] = a[i-1] + d.get(s[i])
print(a)
for _ in range(q):
l,r = M()
if (l<2):
c = a[r-1]
else:
c=a[r-1]-a[l-2]
print(c)
```
No
| 101,464 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Submitted Solution:
```
d={"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,"o":15,"p":16,"q":17,"r":18,"s":19,"t":20,"u":21,"v":22,"w":23,"x":24,"y":25,"z":26}
n,q=map(int,input().split())
s=str(input())
arr=[]
arr.append(d[s[0]])
for i in range(1,n):
x=d[s[i]]
y=arr[-1]
arr.append(x+y)
for i in range(q):
a,b=map(int,input().split())
if a==1:
if b==n:
print(arr[-1])
else:
print(b-1)
```
No
| 101,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
s = input()
v = [0]
for i in range(n):
v.append(v[-1] + (ord(s[i])-96))
print(v)
for _ in range(q):
l, r = map(int, input().split())
print(v[r]-v[l-1])
```
No
| 101,466 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is 10. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
Input
The first line contains two integers n and q (1β€ nβ€ 100 000, 1β€ q β€ 100 000) β the length of the song and the number of questions.
The second line contains one string s β the song, consisting of n lowercase letters of English letters.
Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1 β€ l β€ r β€ n) β the bounds of the question.
Output
Print q lines: for each question print the length of the string obtained by Vasya.
Examples
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
Note
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to 4. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is 7. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length 11.
Submitted Solution:
```
n, q=map(int, input().split())
s=input()
alp={'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20, 'u':21, 'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
li=[0]
sum=0
for i in range(n):
sum+=alp[s[i]]
li.append(sum)
print(li)
for i in range(q):
x, y=map(int, input().split())
print(li[y]-li[x-1])
```
No
| 101,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a non-oriented connected graph of n vertices and n - 1 edges as a beard, if all of its vertices except, perhaps, one, have the degree of 2 or 1 (that is, there exists no more than one vertex, whose degree is more than two). Let us remind you that the degree of a vertex is the number of edges that connect to it.
Let each edge be either black or white. Initially all edges are black.
You are given the description of the beard graph. Your task is to analyze requests of the following types:
* paint the edge number i black. The edge number i is the edge that has this number in the description. It is guaranteed that by the moment of this request the i-th edge is white
* paint the edge number i white. It is guaranteed that by the moment of this request the i-th edge is black
* find the length of the shortest path going only along the black edges between vertices a and b or indicate that no such path exists between them (a path's length is the number of edges in it)
The vertices are numbered with integers from 1 to n, and the edges are numbered with integers from 1 to n - 1.
Input
The first line of the input contains an integer n (2 β€ n β€ 105) β the number of vertices in the graph. Next n - 1 lines contain edges described as the numbers of vertices vi, ui (1 β€ vi, ui β€ n, vi β ui) connected by this edge. It is guaranteed that the given graph is connected and forms a beard graph, and has no self-loops or multiple edges.
The next line contains an integer m (1 β€ m β€ 3Β·105) β the number of requests. Next m lines contain requests in the following form: first a line contains an integer type, which takes values ββfrom 1 to 3, and represents the request type.
If type = 1, then the current request is a request to paint the edge black. In this case, in addition to number type the line should contain integer id (1 β€ id β€ n - 1), which represents the number of the edge to paint.
If type = 2, then the current request is a request to paint the edge white, its form is similar to the previous request.
If type = 3, then the current request is a request to find the distance. In this case, in addition to type, the line should contain two integers a, b (1 β€ a, b β€ n, a can be equal to b) β the numbers of vertices, the distance between which must be found.
The numbers in all lines are separated by exactly one space. The edges are numbered in the order in which they are given in the input.
Output
For each request to "find the distance between vertices a and b" print the result. If there is no path going only along the black edges between vertices a and b, then print "-1" (without the quotes). Print the results in the order of receiving the requests, separate the numbers with spaces or line breaks.
Examples
Input
3
1 2
2 3
7
3 1 2
3 1 3
3 2 3
2 2
3 1 2
3 1 3
3 2 3
Output
1
2
1
1
-1
-1
Input
6
1 5
6 4
2 3
3 5
5 6
6
3 3 4
2 5
3 2 6
3 1 2
2 3
3 3 1
Output
3
-1
3
2
Note
In the first sample vertices 1 and 2 are connected with edge number 1, and vertices 2 and 3 are connected with edge number 2. Before the repainting edge number 2 each vertex is reachable from each one along the black edges. Specifically, the shortest path between 1 and 3 goes along both edges.
If we paint edge number 2 white, vertex 3 will end up cut off from other vertices, that is, no path exists from it to any other vertex along the black edges.
Submitted Solution:
```
from sys import stdin, stdout
def dfs(v, k, l):
global d, t
time[v][0] = t
visit[v] = 1
distance[v] = l
for u in vertices[v]:
if not visit[u]:
t += 1
d[(min(u, v), max(u, v))] = k
k = dfs(u, k + 1, l + 1)
time[v][1] = t
t += 1
return k
def translate(a, b):
ans = []
for v in vertices[a]:
if min(distance[a], distance[b]) <= distance[v] <= max(distance[a], distance[b]):
ans.append(v)
break
for v in vertices[b]:
if min(distance[a], distance[b]) <= distance[v] <= max(distance[a], distance[b]):
ans.append(v)
break
return (d[(min(a, ans[0]), max(a, ans[0]))], d[(min(b, ans[1]), max(b, ans[1]))])
def update(n, value):
tree[n + power - 1] = value
n = n + power - 1
while n // 2:
n //= 2
tree[n] = tree[n * 2] + tree[n * 2 + 1]
def get(l, r, lb, rb, ind):
if l == lb and r == rb:
return tree[ind]
m = (lb + rb) // 2
first, second = 0, 0
if l <= m:
first = get(l, min(m, r), lb, m, ind * 2)
if r > m:
second = get(max(l, m + 1), r, m + 1, rb, ind * 2 + 1)
return first + second
n = int(stdin.readline())
vertices = [[] for i in range(n + 1)]
time = [[0, 0] for i in range(n + 1)]
challengers = []
root = 1
for i in range(n - 1):
a, b = map(int, stdin.readline().split())
challengers.append((a, b))
vertices[a].append(b)
vertices[b].append(a)
for i in range(1, n + 1):
if len(vertices[i]) > 2:
root = i
distance = {}
d = {}
t = 0
visit = [0 for i in range(n + 1)]
dfs(root, 1, 0)
power = 1
while power <= n:
power *= 2
tree = [0 for i in range(2 * power)]
q = int(stdin.readline())
for i in range(q):
s = stdin.readline().split()
if s[0] == '1':
a, b = challengers[int(s[1]) - 1]
update(d[(min(a, b), max(a, b))], 0)
elif s[0] == '2':
a, b = challengers[int(s[1]) - 1]
update(d[(min(a, b), max(a, b))], 1)
else:
typ, a, b = map(int, s)
if a == b:
stdout.write('0\n')
continue
cnt = abs(distance[a] - distance[b])
if time[a][0] <= time[b][0] and time[a][1] >= time[b][1]:
a, b = translate(a, b)
if not get(a, b, 1, power, 1):
stdout.write(str(cnt) + '\n')
else:
stdout.write('-1\n')
elif time[a][0] >= time[b][0] and time[a][1] <= time[b][1]:
a, b = translate(a, b)
if not get(b, a, 1, power, 1):
stdout.write(str(cnt) + '\n')
else:
stdout.write('-1\n')
else:
cnt = distance[a] + distance[b]
a1, b1 = translate(root, a)
a2, b2 = translate(root, b)
if not get(a1, b1, 1, power, 1) and not get(a2, b2, 1, power, 1):
stdout.write(str(cnt) + '\n')
else:
stdout.write('-1\n')
```
No
| 101,468 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Tags: implementation, math
Correct Solution:
```
n=int(input())
if n%2==0:
for i in range(2,n+1,2):
print(i,i-1,end=' ')
else:
print('-1')
```
| 101,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Tags: implementation, math
Correct Solution:
```
n=int(input());U=[];a=''
if n%2:print(-1)
else:
for i in range(1,n+1,2):
U.append(i+1);U.append(i)
for j in U:
a+=str(j)+' '
print(a)
```
| 101,470 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Tags: implementation, math
Correct Solution:
```
n=int(input())
if(n%2==1):
print(-1)
else:
for i in range(1,(n//2)+1):
print(2*i,(2*i)-1,end=' ')
```
| 101,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Tags: implementation, math
Correct Solution:
```
R = lambda: map(int, input().split())
n = int(input())
if n % 2:
print(-1)
else:
for i in range(1,n+1,2):
print(i+1,i,end=' ')
```
| 101,472 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Tags: implementation, math
Correct Solution:
```
n = int(input())
l = []
p = []
if n % 2 == 1:
print(-1)
else:
for i in range(1 , n + 1):
l.append(i)
for i in range(len(l)):
if i % 2 == 0:
p.append(l[i+1])
else:
p.append(l[i-1])
for i in range(len(p)):
print(p[i] , end = ' ')
```
| 101,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Tags: implementation, math
Correct Solution:
```
from math import ceil, log, floor, sqrt
import math
k = 1
def mod_expo(n, p, m):
"""find (n^p)%m"""
result = 1
while p != 0:
if p%2 == 1:
result = (result * n)%m
p //= 2
n = (n * n)%m
return result
def find_order(n):
if n%2 == 0:
#res = x for x in range(n, 0, -1)
print(*[x for x in range(n, 0, -1)], sep=' ')
else:
print(-1)
t = 1
#t = int(input())
while t:
t = t - 1
k, g = 0, 0
points = []
n = int(input())
#a = input()
#b = input()
#n, p, q, r = map(int, input().split())
#n, m = map(int, input().split())
#print(discover())
# = map(int, input().split())
#a = list(map(int, input().strip().split()))[:2*n]
#w = list(map(int, input().strip().split()))[:k]
#for i in range(3):
# x, y = map(int, input().split())
# points.append((x, y))
# s = input()
#if possible_phone_number(n, a):
# print("YES")
#else:
# print("NO")
find_order(n)
#print(find_mx_teams(n, m))
```
| 101,474 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Tags: implementation, math
Correct Solution:
```
#-------------Program-------------
#----KuzlyaevNikita-Codeforces----
#
n=int(input())
if n%2!=0:print(-1)
else:
for i in range(1,n+1,2):
print(i+1,i,end=' ')
```
| 101,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Tags: implementation, math
Correct Solution:
```
n=int(input())
if(n%2==1):
print(-1)
else:
L=list(range(1,n+1))
for i in range(0,n,2):
t=L[i]
L[i]=L[i+1]
L[i+1]=t
for i in range(n-1):
print(L[i],end=" ")
print(L[-1])
```
| 101,476 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Submitted Solution:
```
n = int(input())
if n%2 == 1:
print('-1')
else:
res = ''
for i in range(n,0,-1):
res+=str(i) + ' '
print(res)
```
Yes
| 101,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Submitted Solution:
```
n=int(input())
if n%2!=0:
l=-1
print(l)
else:
a=2
b=1
s=str(a)+" "+str(b)
for i in range(2,n,2):
s+=" "+str(a+2)+" "+str(b+2)
a+=2
b+=2
print(s)
```
Yes
| 101,478 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Submitted Solution:
```
n=int(input())
if n%2==1:
print(-1)
else:
arr1=[2*int(x) for x in range(1,int((n+2)/2))]
arr2=[x-1 for x in arr1]
for i in range(n//2):
print(arr1[i],end=" ")
print(arr2[i],end=" ")
```
Yes
| 101,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Submitted Solution:
```
n=int(input())
c=[]
if(n%2==0):
for i in range(2,n+1,2):
c.append(i)
c.append(i-1)
a=" ".join(str(i) for i in c)
print(a)
else:
print(-1)
```
Yes
| 101,480 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Submitted Solution:
```
n= int(input())
a=[]
for i in range(n):
a.append(i+1)
if n==1:
print("-1")
else:
k=a.pop()
a.insert(0,k)
print(a)
```
No
| 101,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Submitted Solution:
```
# import os
n = int(input())
if n % 2 == 0:
a = [i for i in range(n//2, 0,-1)]
b = [i for i in range(n, n//2, -1)]
print(' '.join(map(str, a+b)))
else:
print(-1)
# 03/01 - 1
# 04/01 - 21
# 05/01 - 27
# 06/01 - 3
```
No
| 101,482 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Submitted Solution:
```
n = int(input())
result = [i for i in range(1,n+1)]
if n ==1:
print(-1)
else:
for i in range(n-1):
if (i+1)%2 != 0:
result[i],result[i+1] = result[i+1],result[i]
for i in result:
print(i,end="")
```
No
| 101,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 β€ i β€ n) (n is the permutation size) the following equations hold ppi = i and pi β i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 β€ n β€ 100) β the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β permutation p, that is perfect. Separate printed numbers by whitespaces.
Examples
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
Submitted Solution:
```
n = 4
if n % 2 != 0:
print(-1)
else:
m = list(range(1, n + 1))
for i in m[::2]:
print(m[i], m[i - 1], end=" ")
```
No
| 101,484 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Tags: implementation, math
Correct Solution:
```
import sys
from fractions import gcd
with sys.stdin as fin, sys.stdout as fout:
n, m, x, y, a, b = map(int, next(fin).split())
d = gcd(a, b)
a //= d
b //= d
k = min(n // a, m // b)
w = k * a
h = k * b
x1 = x - (w + 1) // 2
y1 = y - (h + 1) // 2
x1 = min(x1, n - w)
y1 = min(y1, m - h)
x1 = max(x1, 0)
y1 = max(y1, 0)
print(x1, y1, x1 + w, y1 + h, file=fout)
```
| 101,485 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Tags: implementation, math
Correct Solution:
```
#!/usr/bin/python3
def gcd(a, b):
while a:
a, b = b % a, a
return b
n, m, x, y, a, b = tuple(map(int, input().strip().split()))
g = gcd(a, b)
a //= g
b //= g
k = min(n // a, m // b)
w = k * a
h = k * b
ans = [x - w + w // 2, y - h + h // 2, x + w // 2, y + h // 2]
if ans[0] < 0:
ans[2] -= ans[0]
ans[0] = 0;
if ans[1] < 0:
ans[3] -= ans[1]
ans[1] = 0
if ans[2] > n:
ans[0] -= ans[2] - n
ans[2] = n
if ans[3] > m:
ans[1] -= ans[3] - m
ans[3] = m
print('%d %d %d %d' % tuple(ans))
```
| 101,486 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Tags: implementation, math
Correct Solution:
```
import math
n, m, x, y, a, b = map(int, input().split())
gcd = math.gcd(a, b)
a //= gcd
b //= gcd
max_ratio = min(n // a, m // b)
a *= max_ratio
b *= max_ratio
x1 = max(0, min(x - (a + 1) // 2, n - a))
y1 = max(0, min(y - (b + 1) // 2, m - b))
print(x1, y1, x1 + a, y1 + b)
```
| 101,487 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Tags: implementation, math
Correct Solution:
```
from fractions import gcd
n, m, x, y, a, b = map(int, input().split())
g = gcd(a, b)
a, b = a // g, b // g
k = min(n // a, m // b)
a, b = k * a, k * b
x1, x2 = x - (a - a // 2), x + a // 2
y1, y2 = y - (b - b // 2), y + b // 2
d = max(0, 0 - x1)
x1, x2 = x1 + d, x2 + d
d = max(0, x2 - n)
x1, x2 = x1 - d, x2 - d
d = max(0, 0 - y1)
y1, y2 = y1 + d, y2 + d
d = max(0, y2 - m)
y1, y2 = y1 - d, y2 - d
print(" ".join(map(str, [x1, y1, x2, y2])));
```
| 101,488 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Tags: implementation, math
Correct Solution:
```
import sys
from fractions import gcd
with sys.stdin as fin, sys.stdout as fout:
n, m, x, y, a, b = map(int, next(fin).split())
d = gcd(a, b)
a //= d
b //= d
k = min(n // a, m // b) # >_<
w = k * a
h = k * b
best = tuple([float('inf')] * 3)
for add1 in 0, 1:
for add2 in 0, 1:
x1 = x - w // 2 - add1
y1 = y - h // 2 - add2
cur = ((2 * x1 + w - 2 * x) ** 2 + (2 * y1 + h - 2 * y) ** 2, x1, y1)
if cur < best:
best = cur
x1, y1 = best[1:]
x1 = min(x1, n - w)
y1 = min(y1, m - h)
x1 = max(x1, 0)
y1 = max(y1, 0)
print(x1, y1, x1 + w, y1 + h)
```
| 101,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Tags: implementation, math
Correct Solution:
```
from fractions import gcd
n, m, x, y, a, b = map(int, input().split())
r = gcd(a, b)
a, b = a // r, b // r
r = min(n // a, m // b)
a, b = a * r, b * r
cx, cy = (a + 1) // 2, (b + 1) // 2
dx, dy = min(n - a, max(cx, x) - cx), min(m - b, max(cy, y) - cy)
print(dx, dy, a + dx, b + dy)
# Made By Mostafa_Khaled
```
| 101,490 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Tags: implementation, math
Correct Solution:
```
from fractions import gcd
n, m, x, y, a, b = map(int, input().split())
r = gcd(a, b)
a, b = a // r, b // r
r = min(n // a, m // b)
a, b = a * r, b * r
cx, cy = (a + 1) // 2, (b + 1) // 2
dx, dy = min(n - a, max(cx, x) - cx), min(m - b, max(cy, y) - cy)
print(dx, dy, a + dx, b + dy)
```
| 101,491 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Tags: implementation, math
Correct Solution:
```
from fractions import gcd
n, m, x, y, a, b = map(int, input().split())
k = gcd(a, b)
a //= k
b //= k
times = min(n // a, m // b)
a *= times
b *= times
x1 = x - (a + 1) // 2
y1 = y - (b + 1) // 2
if x1 < 0:
x1 = 0
if y1 < 0:
y1 = 0
if x1 + a > n:
x1 -= (x1 + a - n)
if y1 + b > m:
y1 -= (y1 + b - m)
print(x1, y1, x1 + a, y1 + b)
```
| 101,492 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Submitted Solution:
```
import sys
from fractions import gcd
with sys.stdin as fin, sys.stdout as fout:
n, m, x, y, a, b = map(int, next(fin).split())
d = gcd(a, b)
a //= d
b //= d
k = n // max(a, b)
w = k * a
h = k * b
x1 = x - (w + 1) // 2
y1 = y - (h + 1) // 2
print(x1, y1, x1 + w, y1 + h)
```
No
| 101,493 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Submitted Solution:
```
import math
n, m, x, y, a, b = map(int, input().split())
gcd = math.gcd(a, b)
a //= gcd
b //= gcd
max_ratio = min(n // a, m // b)
#if (a * max_ratio) % 2 == 1 or (b * max_ratio) % 2 == 1:
# max_ratio -= 1
a *= max_ratio
b *= max_ratio
print(x - a // 2, y - b // 2, x + a // 2, y + b // 2)
```
No
| 101,494 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Submitted Solution:
```
import math
n, m, x, y, a, b = map(int, input().split())
gcd = math.gcd(a, b)
a //= gcd
b //= gcd
max_ratio = min(n // a, m // b)
#if (a * max_ratio) % 2 == 1 or (b * max_ratio) % 2 == 1:
# max_ratio -= 1
a *= max_ratio
b *= max_ratio
print(x - (a + 1) // 2, y - (b + 1) // 2, x + a // 2, y + b // 2)
```
No
| 101,495 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
Submitted Solution:
```
import sys
from fractions import gcd
with sys.stdin as fin, sys.stdout as fout:
n, m, x, y, a, b = map(int, next(fin).split())
d = gcd(a, b)
a //= d
b //= d
k = min(n // a, m // b) # >_<
w = k * a
h = k * b
best = tuple([float('inf')] * 3)
for add1 in 0, 1:
for add2 in 0, 1:
x1 = x - w // 2 - add1
y1 = y - h // 2 - add2
cur = ((x1 + w / 2 - x) ** 2 + (y1 + h / 2 - y) ** 2, x1, y1)
if cur < best:
best = cur
print(best[1], best[2], best[1] + w, best[2] + h)
```
No
| 101,496 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows:
* choose indexes i and j (i β j) that haven't been chosen yet;
* round element ai to the nearest integer that isn't more than ai (assign to ai: β ai β);
* round element aj to the nearest integer that isn't less than aj (assign to aj: β aj β).
Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
Input
The first line contains integer n (1 β€ n β€ 2000). The next line contains 2n real numbers a1, a2, ..., a2n (0 β€ ai β€ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.
Output
In a single line print a single real number β the required difference with exactly three digits after the decimal point.
Examples
Input
3
0.000 0.500 0.750 1.000 2.000 3.000
Output
0.250
Input
3
4469.000 6526.000 4864.000 9356.383 7490.000 995.896
Output
0.279
Note
In the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.
Tags: dp, greedy, implementation, math
Correct Solution:
```
n = int(input())
a = list(map(lambda x: int(x.split('.')[1]), input().split()))
s = sum(a) - n * 1000
zero_cnt = a.count(0)
min_add = max(0, zero_cnt - n)
max_add = min(n, zero_cnt)
answ = min(abs(s + i * 1000) for i in range(min_add, max_add + 1))
print('{:d}.{:0>3d}'.format(answ // 1000, answ % 1000))
```
| 101,497 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows:
* choose indexes i and j (i β j) that haven't been chosen yet;
* round element ai to the nearest integer that isn't more than ai (assign to ai: β ai β);
* round element aj to the nearest integer that isn't less than aj (assign to aj: β aj β).
Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
Input
The first line contains integer n (1 β€ n β€ 2000). The next line contains 2n real numbers a1, a2, ..., a2n (0 β€ ai β€ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.
Output
In a single line print a single real number β the required difference with exactly three digits after the decimal point.
Examples
Input
3
0.000 0.500 0.750 1.000 2.000 3.000
Output
0.250
Input
3
4469.000 6526.000 4864.000 9356.383 7490.000 995.896
Output
0.279
Note
In the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.
Tags: dp, greedy, implementation, math
Correct Solution:
```
n, k, s = int(input()), 0, 0
for i in input().split():
j = int(i[-3: ])
if j == 0: k += 1
else: s += j
c = s // 1000 + int(s % 1000 > 500)
a, b = max(0, n - k), min(2 * n - k, n)
if a <= c <= b: s = abs(c * 1000 - s)
else: s = min(abs(a * 1000 - s), abs(b * 1000 - s))
print(str(s // 1000) + '.' + str(s % 1000).zfill(3))
```
| 101,498 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows:
* choose indexes i and j (i β j) that haven't been chosen yet;
* round element ai to the nearest integer that isn't more than ai (assign to ai: β ai β);
* round element aj to the nearest integer that isn't less than aj (assign to aj: β aj β).
Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
Input
The first line contains integer n (1 β€ n β€ 2000). The next line contains 2n real numbers a1, a2, ..., a2n (0 β€ ai β€ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.
Output
In a single line print a single real number β the required difference with exactly three digits after the decimal point.
Examples
Input
3
0.000 0.500 0.750 1.000 2.000 3.000
Output
0.250
Input
3
4469.000 6526.000 4864.000 9356.383 7490.000 995.896
Output
0.279
Note
In the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.
Tags: dp, greedy, implementation, math
Correct Solution:
```
n, t = int(input()), [int(i[-3: ]) for i in input().split()]
k, s = t.count(0), sum(t)
c = s // 1000 + int(s % 1000 > 500)
a, b = max(0, n - k), min(2 * n - k, n)
if a <= c <= b: s = abs(c * 1000 - s)
else: s = min(abs(a * 1000 - s), abs(b * 1000 - s))
print(str(s // 1000) + '.' + str(s % 1000).zfill(3))
```
| 101,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.