message stringlengths 2 43.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 853 107k | cluster float64 24 24 | __index_level_0__ int64 1.71k 214k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | instruction | 0 | 100,816 | 24 | 201,632 |
Tags: brute force, greedy
Correct Solution:
```
n,k=list(map(int,input().split()))
ans,c=0,0
while k>0 and n>0:
if n % 10 == 0: k -= 1
else: ans += 1
n //= 10
c += 1
print(ans if n>0 else max(0,c-1))
``` | output | 1 | 100,816 | 24 | 201,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | instruction | 0 | 100,817 | 24 | 201,634 |
Tags: brute force, greedy
Correct Solution:
```
n,k=map(int,input().split())
if(n==0):
print(0)
exit()
x=[]
while(n>0):
x.append(n%10)
n=n//10
c1=0
c2=0
for i in range (len(x)):
if(x[i]==0):
c1+=1
if(c1==k):
break
if(x[i]!=0):
c2+=1
#print(c1,c2)
if(c1<k):
print(len(x)-1)
else:
print(c2)
``` | output | 1 | 100,817 | 24 | 201,635 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | instruction | 0 | 100,818 | 24 | 201,636 |
Tags: brute force, greedy
Correct Solution:
```
n,k = [x for x in input().split()]
k = int(k)
ans = 0
stack = 0
if k == 0:
print(0)
if n.count('0') < k:
print(len(n)-1)
else:
for i in n[::-1]:
if stack == k:
break
if i=="0":
stack+=1
else:
ans += 1
print(ans)
``` | output | 1 | 100,818 | 24 | 201,637 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | instruction | 0 | 100,819 | 24 | 201,638 |
Tags: brute force, greedy
Correct Solution:
```
n,k = input().split()
k = int(k)
n = list(map(int,list(n)))
l = len(n)
j = l-1
while(j>-1 and k>0):
if(n[j]!=0):
del n[j]
else:
k -= 1
j -= 1
if(n[0]==0):
print(l-1)
else:
print(l-len(n))
``` | output | 1 | 100,819 | 24 | 201,639 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | instruction | 0 | 100,820 | 24 | 201,640 |
Tags: brute force, greedy
Correct Solution:
```
n, k = input().split()
n, k = n[::-1], int(k)
r = 0
for i in range(len(n)):
if n[i] != '0':
r += 1
if i-r+1 == k:
break
else:
r = len(n)-1
print(r)
``` | output | 1 | 100,820 | 24 | 201,641 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | instruction | 0 | 100,821 | 24 | 201,642 |
Tags: brute force, greedy
Correct Solution:
```
n, k = input().split()
n = list(n)
k = int(k)
zeroes = 0
digits_to_remove = 0
i = len(n) - 1
while True:
if zeroes < k:
if i == 0:
digits_to_remove += len(n) - 1
break
elif n[i] == '0':
zeroes += 1
else:
del n[i]
digits_to_remove += 1
i -= 1
else:
break
print(digits_to_remove)
``` | output | 1 | 100,821 | 24 | 201,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | instruction | 0 | 100,822 | 24 | 201,644 |
Tags: brute force, greedy
Correct Solution:
```
n,m=input().split();n,m=list(n)[::-1],int(m);k=0;i=0;ans=0;p=len(n)
if p<=m:print(p-1)
else:
if n.count('0')<m:print(p-1)
else:
while k!=m and i<p:
if n[i]=='0':k+=1
else:ans+=1
i+=1
print(ans)
``` | output | 1 | 100,822 | 24 | 201,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | instruction | 0 | 100,823 | 24 | 201,646 |
Tags: brute force, greedy
Correct Solution:
```
n,k=map(str,input().split())
a=list(n)
k=int(k)
if((10**k)>int(n)):
print(len(n)-1)
else:
if((int(n)%(10**k))==0):
print(0)
else:
c=0
z=0
for i in range(len(a)-1,-1,-1):
if(z==k):
break
if(a[i]!='0'):
c=c+1
if(a[i]=='0'):
z=z+1
if(z<k):
print(len(a)-1)
else:
print(c)
``` | output | 1 | 100,823 | 24 | 201,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.
Submitted Solution:
```
L = input()
L = L.split()
n = L[0]
k = int(L[1])
def Div(N, K):
N = int(N)
if N%10**K == 0:
return True
else:
return False
c = 0
f = len(n)
while f != 1:
f -= 1
if n[f] != '0' and not(Div(n,k)):
b = n[:f] + n[f +1:]
n = b
c += 1
else:
b = n
if int(n) == 0:
print (c)
else:
nd = len(b)
nceros = nd -1
if nceros < k:
c = nceros + c
print (c)
``` | instruction | 0 | 100,824 | 24 | 201,648 |
Yes | output | 1 | 100,824 | 24 | 201,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.
Submitted Solution:
```
n, k = list(map(int, input().split()))
n = list(str(n))
a = len(n)
if n.count('0') < k:
print(a-1)
else:
cz = 0
ca = 0
for i in n[::-1]:
if i == '0':
cz += 1
else:
ca += 1
if cz == k:
print(ca)
break
``` | instruction | 0 | 100,825 | 24 | 201,650 |
Yes | output | 1 | 100,825 | 24 | 201,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.
Submitted Solution:
```
s, k = input().split()
k = int(k)
v, w, l = 0, 0, len(s)
for i in reversed(range(l)):
if s[i] == '0':
v += 1
elif not v >= k:
w += 1
if v >= k:
print(w)
else:
print(l-1)
``` | instruction | 0 | 100,826 | 24 | 201,652 |
Yes | output | 1 | 100,826 | 24 | 201,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.
Submitted Solution:
```
a = list(input().split())
n = a[0]
k = int(a[1])
c = 0
f = 0
for x in range(-1, -len(n)-1, -1):
if n[x] == "0":
c = c + 1
if c == k:
print( -x-k )
f = 1
break
if f == 0:
print(len(n) - 1)
``` | instruction | 0 | 100,827 | 24 | 201,654 |
Yes | output | 1 | 100,827 | 24 | 201,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.
Submitted Solution:
```
n,k=list(map(int,input().split()))
ans,c=0,0
while k>0 and n>0:
if n % 10 == 0: k -= 1
else: ans += 1
n //= 10
c += 1
print(ans if n>0 else c-1)
``` | instruction | 0 | 100,828 | 24 | 201,656 |
No | output | 1 | 100,828 | 24 | 201,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.
Submitted Solution:
```
n,k=input ().split (); k = int (k); n=n [::-1];
for i in range (0,100) :
if n [:i].count ("0")>=k :
print (i);
break;
else : print (str (len (n)-1))
``` | instruction | 0 | 100,829 | 24 | 201,658 |
No | output | 1 | 100,829 | 24 | 201,659 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.
Submitted Solution:
```
n,k=map(str,input().strip().split())
k=int(k)
num=str(10**k)
if(len(n)<len(num)):
print(len(n)-1)
else:
c,z=0,0
for i in range(len(n)-1,-1,-1):
if(n[i]!='0'):
c+=1
else:
z+=1
if(z==k):
break
print(c)
``` | instruction | 0 | 100,830 | 24 | 201,660 |
No | output | 1 | 100,830 | 24 | 201,661 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
Input
The only line of the input contains two integer numbers n and k (0 β€ n β€ 2 000 000 000, 1 β€ k β€ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.
Output
Print w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).
Examples
Input
30020 3
Output
1
Input
100 9
Output
2
Input
10203049 2
Output
3
Note
In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number.
Submitted Solution:
```
'''input
100 9
'''
n, k = map(int, input().split())
if str(n).count('0') >= k:
x = str(n)[::-1]
for l in range(1,len(x)):
if x[:l].count('0') == k:
print(l-k)
else:
print(len(str(n))-1)
``` | instruction | 0 | 100,831 | 24 | 201,662 |
No | output | 1 | 100,831 | 24 | 201,663 |
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 | instruction | 0 | 101,416 | 24 | 202,832 |
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)
``` | output | 1 | 101,416 | 24 | 202,833 |
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 | instruction | 0 | 101,417 | 24 | 202,834 |
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)
``` | output | 1 | 101,417 | 24 | 202,835 |
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 | instruction | 0 | 101,418 | 24 | 202,836 |
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)
``` | output | 1 | 101,418 | 24 | 202,837 |
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 | instruction | 0 | 101,419 | 24 | 202,838 |
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)
``` | output | 1 | 101,419 | 24 | 202,839 |
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 | instruction | 0 | 101,420 | 24 | 202,840 |
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)
``` | output | 1 | 101,420 | 24 | 202,841 |
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 | instruction | 0 | 101,421 | 24 | 202,842 |
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)
``` | output | 1 | 101,421 | 24 | 202,843 |
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 | instruction | 0 | 101,422 | 24 | 202,844 |
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)
``` | output | 1 | 101,422 | 24 | 202,845 |
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 | instruction | 0 | 101,423 | 24 | 202,846 |
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)
``` | output | 1 | 101,423 | 24 | 202,847 |
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))
``` | instruction | 0 | 101,424 | 24 | 202,848 |
Yes | output | 1 | 101,424 | 24 | 202,849 |
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)
``` | instruction | 0 | 101,425 | 24 | 202,850 |
Yes | output | 1 | 101,425 | 24 | 202,851 |
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()
``` | instruction | 0 | 101,426 | 24 | 202,852 |
Yes | output | 1 | 101,426 | 24 | 202,853 |
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)
``` | instruction | 0 | 101,427 | 24 | 202,854 |
Yes | output | 1 | 101,427 | 24 | 202,855 |
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)
``` | instruction | 0 | 101,428 | 24 | 202,856 |
No | output | 1 | 101,428 | 24 | 202,857 |
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)
``` | instruction | 0 | 101,429 | 24 | 202,858 |
No | output | 1 | 101,429 | 24 | 202,859 |
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)
``` | instruction | 0 | 101,430 | 24 | 202,860 |
No | output | 1 | 101,430 | 24 | 202,861 |
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)
``` | instruction | 0 | 101,431 | 24 | 202,862 |
No | output | 1 | 101,431 | 24 | 202,863 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. | instruction | 0 | 102,603 | 24 | 205,206 |
Tags: dp, sortings
Correct Solution:
```
from sys import stdin
input = stdin.readline
n = int(input())
T = 2001
t, d, p, idx = [], [], [], []
ans = []
arr = []
for i in range(n):
a, b, c = map(int, input().split())
arr.append([a, b, c, i])
arr.sort(key=lambda x: x[1])
for i in arr:
t.append(i[0]); d.append(i[1]); p.append(i[2]); idx.append(i[3])
dp = [[0 for j in range(n)] for i in range(T)]
for time in range(1, T):
for i in range(n):
#dp[time][i] = max(dp[time - 1][i], dp[time][i - 1])
dp[time][i] = dp[time][i - 1]
if d[i] > time >= t[i]:
if i:
dp[time][i] = max(dp[time][i], p[i] + dp[time - t[i]][i - 1])
else:
dp[time][i] = p[i]
b = [0, [0 ,0]]
for i in range(T):
for j in range(n):
if b[0] < dp[i][j]:
b = [dp[i][j], [i, j]]
print(b[0])
b = b[1]
while dp[b[0]][b[1]] and b[0] > -1:
if b[1] and dp[b[0]][b[1]] != dp[b[0]][b[1] - 1]:
ans.append(b[1])
b[0] -= t[b[1]]
elif b[1] == 0:
if dp[b[0]][b[1]]:
ans.append(b[1])
break
b[1] -= 1
print(len(ans))
for i in ans[::-1]:
print(idx[i] + 1, end=' ')
``` | output | 1 | 102,603 | 24 | 205,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. | instruction | 0 | 102,604 | 24 | 205,208 |
Tags: dp, sortings
Correct Solution:
```
n = int(input())
items = []
max_time = 0
for i in range(1,n+1):
t,d,p = map(int,input().split())
max_time = max(max_time, d)
items.append((t,d,p,i))
items.sort(key=lambda x: x[1])
dp = [[(0,[]) for _ in range(n+1)] for _ in range(max_time+1)]
for time in range(1, max_time+1):
for it in range(1, n+1):
if time < items[it-1][0] or time >= items[it-1][1]:
dp[time][it] = max(dp[time][it-1], dp[time-1][it])
else:
pick = dp[time-items[it-1][0]][it-1][0] + items[it-1][2]
if dp[time][it-1][0] > pick :
dp[time][it] = max(dp[time][it-1], dp[time-1][it])
else:
dp[time][it] = (dp[time-items[it-1][0]][it-1][0] + items[it-1][2], list(dp[time-items[it-1][0]][it-1][1]))
dp[time][it][1].append(items[it-1][3])
#print(dp)
res = max(dp[max_time])
print(res[0])
print(len(res[1]))
print(*res[1])
``` | output | 1 | 102,604 | 24 | 205,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. | instruction | 0 | 102,605 | 24 | 205,210 |
Tags: dp, sortings
Correct Solution:
```
from functools import lru_cache
def readints():
return [int(obj) for obj in input().strip().split()]
class Solver:
def main(self):
n = readints()[0]
self.t, self.d, self.p = [], [], []
for i in range(n):
t1, d1, p1 = readints()
self.t.append(t1)
self.d.append(d1)
self.p.append(p1)
self.backtrack = []
sd = max(self.d) + 1
for i in range(n+1):
self.backtrack.append([])
for j in range(sd):
self.backtrack[i].append(0)
triples = zip(self.t, self.d, self.p, range(1, n+1))
triples = sorted(triples, key=lambda x: x[1])
self.t, self.d, self.p, self.indexes = [0], [0], [0], []
for i in range(n):
self.t.append(triples[i][0])
self.d.append(triples[i][1])
self.p.append(triples[i][2])
self.indexes.append(triples[i][3])
self.f = []
for i in range(n+1):
self.f.append([])
for j in range(sd):
self.f[i].append(0)
for i in range(1, n+1):
for d in range(sd):
if d - self.t[i] >= 0 and d < self.d[i] and self.t[i] < self.d[i]:
data = self.f[i - 1][d - self.t[i]]
if data + self.p[i] > self.f[i][d]:
self.f[i][d] = data + self.p[i]
self.backtrack[i][d] = i
data = self.f[i - 1][d]
if data > self.f[i][d]:
self.f[i][d] = data
self.backtrack[i][d] = 0
ans = 0
res = []
best = None
for i in range(sd):
data = self.f[n][i]
if data > ans:
ans = data
best = (n, i)
if best is None:
print('0\n0\n')
return
i = best[0]
s = best[1]
while i > 0:
if self.backtrack[i][s] != 0:
res.append(self.backtrack[i][s])
s -= self.t[self.backtrack[i][s]]
i -= 1
print(ans)
print(len(res))
print(' '.join(str(self.indexes[item - 1]) for item in reversed(res)))
Solver().main()
``` | output | 1 | 102,605 | 24 | 205,211 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. | instruction | 0 | 102,606 | 24 | 205,212 |
Tags: dp, sortings
Correct Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2*10**5+10)
write = lambda x: sys.stdout.write(x+"\n")
debug = lambda x: sys.stderr.write(x+"\n")
writef = lambda x: print("{:.12f}".format(x))
n = int(input())
tdp = [list(map(int, input().split())) for _ in range(n)]
index = list(range(n))
index.sort(key=lambda i: tdp[i][1])
# tdp.sort(key=lambda item: (item[1]))
T = max([item[1] for item in tdp])
dp = [0]*(T+1)
ps = []
# for i,(t,d,p) in enumerate(tdp):
for ind in range(n):
i = index[ind]
t,d,p = tdp[i]
ndp = dp[:]
prv = [(k, -1) for k in range(T+1)]
for j in range(T+1):
if j+t<d:
if ndp[j+t]<dp[j]+p:
ndp[j+t] = dp[j]+p
prv[j+t] = (j, i)
dp = ndp
ps.append(prv)
# print(dp)
ans = max(dp)
res = []
for j in range(T+1)[::-1]:
if dp[j]==ans:
for i in range(n)[::-1]:
jj,ii = ps[i][j]
if ii>=0:
res.append(ii+1)
j = jj
break
res = res[::-1]
print(ans)
print(len(res))
write(" ".join(map(str, res)))
``` | output | 1 | 102,606 | 24 | 205,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. | instruction | 0 | 102,607 | 24 | 205,214 |
Tags: dp, sortings
Correct Solution:
```
P = [0] * 2001
S = [[] for i in range(2001)]
q = [list(map(int, input().split())) + [str(i + 1)] for i in range(int(input()))]
q.sort(key=lambda q: q[1])
for t, d, p, i in q:
for x in range(t, d)[::-1]:
if P[x] < P[x - t] + p:
P[x] = P[x - t] + p
S[x] = S[x - t] + [i]
k = P.index(max(P))
print('\n'.join([str(P[k]), str(len(S[k])), ' '.join(S[k])]))
``` | output | 1 | 102,607 | 24 | 205,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. | instruction | 0 | 102,608 | 24 | 205,216 |
Tags: dp, sortings
Correct Solution:
```
from sys import stdin, stdout
T = 2001
INF = int(1e9)
n = int(stdin.readline())
items = []
for i in range(n):
c, d, t = map(int, stdin.readline().split())
items.append((d, c, t, i+1))
items.sort()
dp = [[None for i in range(T)] for j in range(n)]
def solve(pos, time):
if pos >= n or time >= T:
return 0
if dp[pos][time] is not None:
return dp[pos][time]
d, c, t, i = items[pos]
ans = solve(pos+1, time)
if time + c < d:
ans = max(ans, solve(pos+1, time + c) + t)
dp[pos][time] = ans
return ans
ans = []
def recover(pos, time):
global ans
if pos >= n or time >= T:
return
d, c, t, i = items[pos]
if solve(pos+1, time) == solve(pos, time):
recover(pos+1, time)
else:
ans.append(i)
recover(pos+1, time + c)
stdout.write(str(solve(0, 0)) + '\n')
recover(0, 0)
stdout.write(str(len(ans)) + '\n')
for i in ans:
stdout.write(str(i) + ' ')
stdout.write('\n')
``` | output | 1 | 102,608 | 24 | 205,217 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. | instruction | 0 | 102,609 | 24 | 205,218 |
Tags: dp, sortings
Correct Solution:
```
n = int(input())
a = []
for i in range(n):
t,d,p = map(int,input().split())
a.append([t,d,p,i+1])
a.sort(key = lambda x: x[1])
d = {0: [0,[]]}
for i in a:
e = {}
for j in d:
if d[j][0] + i[0] < i[1]:
if j + i[2] in d:
if d[j][0]+i[0] < d[j+i[2]][0]:
e[j+i[2]] = [d[j][0]+i[0],d[j][1]+[i[3]]]
else:
e[j+i[2]] = [d[j][0]+i[0],d[j][1]+[i[3]]]
d.update(e)
t = max(d)
print(t)
k = d[t][1]
print(len(k))
k = list(map(str,k))
print(' '.join(k))
``` | output | 1 | 102,609 | 24 | 205,219 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. | instruction | 0 | 102,610 | 24 | 205,220 |
Tags: dp, sortings
Correct Solution:
```
import os
import sys
import re
from collections import OrderedDict
if 'PYCHARM' in os.environ:
sys.stdin = open('in', 'r')
n = int(input())
things = []
for i in range(n):
t, d, p = map(int, input().split())
things.append((d, t, p, i + 1))
things.sort()
D = 2001
f = [[0] * D]
w = [[False] * D]
for i in range(n):
thing = things[i]
w.append([False] * D)
f.append(list(f[i]))
for j in range(D):
ni = j + thing[1]
nv = f[i][j] + thing[2]
if ni < thing[0]:
if f[i + 1][ni] < nv:
f[i + 1][ni] = nv
w[i + 1][ni] = True
ind = 0
for i in range(D):
if f[n][i] > f[n][ind]:
ind = i
print(f[n][ind])
ans = []
for i in range(n, 0, -1):
if w[i][ind]:
ind -= things[i - 1][1]
ans.append(things[i - 1][3])
print(len(ans))
print(*reversed(ans))
``` | output | 1 | 102,610 | 24 | 205,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Submitted Solution:
```
import copy
n = int(input())
arr = []
m = 0
for er in range(n):
temp = list(map(int,input().split(" ")))
temp.append(er+1)
if(temp[0]<temp[1]):
arr.append(temp)
if(temp[1]>m):
m = temp[1]
else:
n-=1
arr.sort(key = lambda x:x[1])
#print(arr)
temp=[]
for i in range(n):
temp.append([0])
com = []
com.append(temp)
total = [0,0]
for i in range(1,m+1):
temp = []
for j in range(n+1):
if(j==0):
temp.append([0])
else:
p=arr[j-1]
if(p[0]>i or p[1]<=i):
temp.append(temp[j-1])
else:
te = i - p[0]
ty = copy.deepcopy(com[te][j-1])
ty[0]+=p[2]
ty.append(j)
if(total[0]<ty[0]):
total = ty
if(temp[j-1][0]<ty[0]):
temp.append(ty)
else:
temp.append(temp[j-1])
#print(temp , " temp")
com.append(temp)
#print(com)
print(total[0])
if(total[0]>0):
print(len(total)-1)
for i in range(1,len(total)):
print(arr[total[i]-1][3] , end = " ")
else:
print("0")
``` | instruction | 0 | 102,611 | 24 | 205,222 |
Yes | output | 1 | 102,611 | 24 | 205,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
#setrecursionlimit(300000)
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
sys.setrecursionlimit(300000)
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=0, func=lambda a, b: max(a, b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------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------------------------------------
n=int(input())
ma=0
l=[]
time=[]
for i in range(n):
s=list(map(int,input().split()))
ma=max(ma,s[1])
l.append(s+[i+1])
time.append(s[1])
l=sort_list(l,time)
dp=[[[] for i in range(ma+1)]for j in range(n)]
dp1=[[0 for i in range(ma+1)]for j in range(n)]
for i in range(ma+1):
if l[0][0]<i<=l[0][1]:
dp1[0][i]=l[0][2]
dp[0][i]=[l[0][-1]]
for i in range(1,n):
for j in range(ma+1):
if j-l[i][0]>0 and j<=l[i][1]:
dp1[i][j]=max(dp1[i-1][j],dp1[i-1][j-l[i][0]]+l[i][2])
if dp1[i][j]==dp1[i-1][j]:
dp[i][j]=dp[i-1][j]+[]
else:
dp[i][j]=dp[i-1][j-l[i][0]]+[l[i][-1]]
else:
dp1[i][j]=dp1[i-1][j]
dp[i][j]=dp[i-1][j]+[]
ans=max(dp1[-1])
print(ans)
ind=dp1[-1].index(ans)
print(len(dp[-1][ind]))
print(*dp[-1][ind])
``` | instruction | 0 | 102,612 | 24 | 205,224 |
Yes | output | 1 | 102,612 | 24 | 205,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Submitted Solution:
```
from sys import stdin
n = int(stdin.readline())
items = []
for i in range(n):
t,d,p = [int(x) for x in stdin.readline().split()]
items.append((d,t,p,i))
items.sort()
mem = [{} for x in range(n)]
mem2 = [{} for x in range(n)]
def best(time,x):
time += items[x][1]
if time in mem[x]:
return mem[x][time]
if time >= items[x][0]:
mem[x][time] = 0
mem2[x][time] = -1
return 0
top = 0
top2 = -1
for i in range(x+1,n):
temp = best(time,i)
if temp > top:
top = temp
top2 = i
mem[x][time] = top+items[x][2]
mem2[x][time] = top2
return mem[x][time]
top = -1
l = []
for x in range(n):
b = best(0,x)
if b > top:
top = b
#print('new',x,top)
l = []
c = x
time = 0
while c != -1:
time += items[c][1]
l.append(items[c][3])
if time in mem2[c]:
c = mem2[c][time]
else:
c = -1
print(top)
if top != 0:
print(len(l))
print(' '.join([str(x+1) for x in l]))
else:
print(0)
print()
``` | instruction | 0 | 102,613 | 24 | 205,226 |
Yes | output | 1 | 102,613 | 24 | 205,227 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
'''
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
'''
#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=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)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=n
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
res=mid
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=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)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=n
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
res=mid
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
t=1
#t=int(input())
for _ in range (t):
n=int(input())
#n,x=map(int,input().split())
#a=list(map(int,input().split()))
#b=list(map(int,input().split()))
#s=input()
#n=len(s)
a=[]
m=0
for i in range (n):
tm,d,p=map(int,input().split())
a.append([d,tm,p,i+1])
m=max(m,d)
a.sort()
dp=[0]*(m+1)
result=[set()]*(m+1)
for i in range (n):
for j in range (a[i][0]-1,a[i][1]-1,-1):
curr=dp[j-a[i][1]]+a[i][2]
if curr>dp[j]:
dp[j]=curr
result[j]=result[j-a[i][1]].copy()
result[j].add(a[i][3])
#print(dp)
#print(result)
mx=max(dp)
ans=None
for i in range (m+1):
if dp[i]==mx:
ans=result[i]
print(mx)
print(len(ans))
print(*ans)
``` | instruction | 0 | 102,614 | 24 | 205,228 |
Yes | output | 1 | 102,614 | 24 | 205,229 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Submitted Solution:
```
import os
import sys
import re
from collections import OrderedDict
if 'PYCHARM' in os.environ:
sys.stdin = open('in', 'r')
n = int(input())
things = []
for i in range(n):
t, d, p = map(int, input().split())
things.append((d, t, p, i + 1))
things.sort()
D = 2001
f = [0] * D
p = [-1] * D
pi = [-1] * D
for thing in things:
for i in reversed(range(D)):
ni = i + thing[1]
nv = f[i] + thing[2]
if ni <= thing[0]:
if f[ni] < nv:
f[ni] = nv
p[ni] = thing[3]
pi[ni] = i
ind = 0
for i in range(0, D):
if f[i] > f[ind]:
ind = i
print(f[ind])
ans = []
while ind:
ans.append(p[ind])
ind = pi[ind]
print(len(ans))
print(*reversed(ans))
``` | instruction | 0 | 102,615 | 24 | 205,230 |
No | output | 1 | 102,615 | 24 | 205,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Submitted Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
"""
created by shhuan at 2017/10/4 21:10
"""
N = int(input())
M = []
for i in range(N):
M.append([int(x) for x in input().split()])
N = len(M)
T = [0] + [x[0] for x in M]
D = [0] + [x[1] for x in M]
P = [0] + [x[2] for x in M]
dmax = max(D)
# dp[t][i]ε³ζΆι΄tε
θ½ε€ζ―ζηεiδΈͺη©εηζε€§η©εδ»·εΌ
dp = [[0 for _ in range(N+1)] for _ in range(dmax)]
track = [[0 for _ in range(N+1)] for _ in range(dmax)]
for t in range(dmax):
for i in range(1, N+1):
ti = t-T[i]
if T[i] <= t < D[i] and ti >= 0:
dp[t][i] = max(dp[t][i-1], dp[ti][i-1] + P[i])
if dp[t][i-1] > dp[ti][i-1]+P[i]:
track[t][i] = (t, i-1, -1)
else:
track[t][i] = (ti, i-1, i)
else:
dp[t][i] = dp[t][i-1]
track[t][i] = (t, i-1, -1)
print(dp[dmax-1][N])
t, i, j = dmax-1, N, -1
res = []
while t > 0 and i > 0:
t, i, j = track[t][i]
if j > 0:
res.append(j)
print(len(res))
print(' '.join([str(x) for x in reversed(res)]))
``` | instruction | 0 | 102,616 | 24 | 205,232 |
No | output | 1 | 102,616 | 24 | 205,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Submitted Solution:
```
def count_spaces(l, t, x):
# up to ind x.
total = prev = 0; n = len(l)
for i in range(x + 1):
total += l[i][1] - prev
prev = l[i][1] + t[l[i][0]]
return total
def move_blocks(x, dist, l, t):
# blocks up to x will move.
last = -1
gaps = []
for i in range(x, 0, -1):
gap = l[i][1] - (l[i - 1][1] + t[l[i - 1][0]])
gaps.append(gap)
if dist > gap:
dist -= gap
else:
if gap > dist:
gaps[-1] = dist
last = i
dist = 0
break
if dist > 0:
last = 0
gaps.append(dist)
#print(gaps, last, x, "ago")
pref = 0
for j in range(last, x + 1): # == len(gaps), prob
#pref += gaps[j - last] # 0 1 2..
pref += gaps[-(j - last + 1)] # -1 -2 -3..
l[j][1] -= pref
def main():
n = int(input())
t = []; d = []; p = []; v = []
nu = 0
for i in range(n):
ti, di, pi = map(int, input().split())
if ti >= di:
continue
di -= 1
t.append(ti); d.append(di); p.append(pi)
v.append(nu)
nu += 1
v.sort(key = lambda x : [p[x] / d[x], d[x]], reverse = True)
l = []
#print(v)
for idx in v:
#print(l, "hello", idx)
placed = False
for j in range(len(l) - 1, -1, -1):
el = l[j]
#print(el, "jumankjo", d, t, idx)
if d[idx] >= el[1] + t[el[0]]: # back of new after back of old
placed = True
front_diff = el[1] + t[el[0]] - (d[idx] - t[idx]) # overlap btwn old back and new front
if j == len(l) - 1:
back_diff = 0
else:
#back_diff = max(0, d[idx] - (l[j + 1][1] + t[l[j + 1][0]])) # overlap btwn back of new and front of next old
back_diff = max(0, d[idx] - l[j + 1][1])
if abs(front_diff) >= back_diff:
diff = max(0, front_diff) + back_diff
else:
diff = back_diff + front_diff
#print(front_diff, back_diff, diff)
if diff == 0:
#l.append((idx, d[idx] - t[idx]))
l.insert(j + 1, [idx, d[idx] - t[idx]])
else:
spaces = count_spaces(l, t, j)
#print(spaces)
if spaces >= diff:
move_blocks(j, diff, l, t)
#l.insert(j + 1, [idx, d[idx] - t[idx]])
#l.insert(j + 1, [idx, l[j][1] + t[l[j][0]]])
l.insert(j + 1, [idx, l[j][1] + t[l[j][0]] - back_diff])
break
#print("apple", placed)
if not placed:
if len(l) == 0:
l.append([idx, d[idx] - t[idx]])
elif l[0][1] >= t[idx]:
#l.append((idx, l[0][1] - t[idx]))
l.insert(0, [idx, l[0][1] - t[idx]])
o = []; total = 0
#print(l)
for k in range(len(l)):
total += p[l[k][0]]
o.append(l[k][0] + 1)
print(total)
print(len(o))
print(*o)
main()
'''
try:
main()
except Exception as e:
print(e)
'''
``` | instruction | 0 | 102,617 | 24 | 205,234 |
No | output | 1 | 102,617 | 24 | 205,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is in really serious trouble β his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β₯ di, then i-th item cannot be saved.
Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β in ta + tb seconds after fire started.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of items in Polycarp's house.
Each of the following n lines contains three integers ti, di, pi (1 β€ ti β€ 20, 1 β€ di β€ 2 000, 1 β€ pi β€ 20) β the time needed to save the item i, the time after which the item i will burn completely and the value of item i.
Output
In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β the number of items in the desired set. In the third line print m distinct integers β numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.
Examples
Input
3
3 7 4
2 6 5
3 7 6
Output
11
2
2 3
Input
2
5 6 1
3 3 5
Output
1
1
1
Note
In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.
In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.
Submitted Solution:
```
n = int(input())
t, d, p = [], [], []
for _ in range(n):
a, b, c = map(int, input().split())
t.append(a); d.append(b); p.append(c)
dp = [[0, -1] for i in range(10)]
for i in range(1, 10):
# dp[i] = dp[i - 1].copy()
for j in range(n):
if d[j] > i >= t[j] and dp[i][0] < p[j] + dp[i - t[j]][0]:
dp[i][0] = p[j] + dp[i - t[j]][0]
dp[i][1] = j
print(max(dp)[0])
i = dp.index(max(dp))
ans = []
while i > 0 and dp[i][1] != -1:
ans.append(dp[i][1] + 1)
i = dp[i][1]
print(len(ans))
print(*ans[::-1])
``` | instruction | 0 | 102,618 | 24 | 205,236 |
No | output | 1 | 102,618 | 24 | 205,237 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second.
Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 β€ l_i < r_i β€ a).
There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 β€ x_i β€ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas.
During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i β€ x and x + 1 β€ r_i).
The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.
Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.
Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.
Input
The first line contains three integers a, n and m (1 β€ a, m β€ 2000, 1 β€ n β€ βa/2β) β the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas.
Each of the next n lines contains two integers l_i and r_i (0 β€ l_i < r_i β€ a) β the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i.
Each of the next m lines contains two integers x_i and p_i (0 β€ x_i β€ a, 1 β€ p_i β€ 10^5) β the location and the weight of the i-th umbrella.
Output
Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.
Examples
Input
10 2 4
3 7
8 10
0 10
3 4
8 1
1 2
Output
14
Input
10 1 1
0 9
0 5
Output
45
Input
10 1 1
0 9
1 5
Output
-1
Note
In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14).
In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. | instruction | 0 | 102,673 | 24 | 205,346 |
Tags: dp
Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict, namedtuple
from math import sqrt, factorial, gcd, ceil, atan, pi
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
# def input(): return sys.stdin.buffer.readline().decode('utf-8')
import string
import operator
# string.ascii_lowercase
from bisect import bisect_left, bisect_right
from functools import lru_cache, reduce
MOD = int(1e9)+7
INF = float('inf')
def solve():
a, n, m = [int(x) for x in input().split()]
rain = [0] * (a + 1)
for _ in range(n):
l, r = [int(x) for x in input().split()]
for i in range(l + 1, r + 1):
rain[i] = 1
umb = []
for _ in range(m):
x, p = [int(x) for x in input().split()]
umb.append((x, p))
umb.sort()
dp = [INF for _ in range(a + 1)]
dp[0] = 0
for i in range(1, a + 1):
if rain[i]:
for x, p in umb:
if x >= i: break
dp[i] = min(dp[i], dp[x] + p * (i - x))
else:
dp[i] = dp[i-1]
if dp[a] == INF:
print(-1)
else:
print(dp[a])
t = 1
# t = int(input())
for case in range(1,t+1):
ans = solve()
"""
1 2
dp[x] = min()
"""
``` | output | 1 | 102,673 | 24 | 205,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second.
Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 β€ l_i < r_i β€ a).
There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 β€ x_i β€ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas.
During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i β€ x and x + 1 β€ r_i).
The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.
Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.
Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.
Input
The first line contains three integers a, n and m (1 β€ a, m β€ 2000, 1 β€ n β€ βa/2β) β the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas.
Each of the next n lines contains two integers l_i and r_i (0 β€ l_i < r_i β€ a) β the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i.
Each of the next m lines contains two integers x_i and p_i (0 β€ x_i β€ a, 1 β€ p_i β€ 10^5) β the location and the weight of the i-th umbrella.
Output
Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.
Examples
Input
10 2 4
3 7
8 10
0 10
3 4
8 1
1 2
Output
14
Input
10 1 1
0 9
0 5
Output
45
Input
10 1 1
0 9
1 5
Output
-1
Note
In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14).
In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. | instruction | 0 | 102,674 | 24 | 205,348 |
Tags: dp
Correct Solution:
```
# Author: S Mahesh Raju
# Username: maheshraju2020
# Date: 03/07/2020
from sys import stdin,stdout
from math import gcd, ceil, sqrt
from collections import Counter
ii1 = lambda: int(stdin.readline().strip())
is1 = lambda: stdin.readline().strip()
iia = lambda: list(map(int, stdin.readline().strip().split()))
isa = lambda: stdin.readline().strip().split()
mod = 1000000007
a, n, m = iia()
rain = []
for _ in range(n):
l, r = iia()
for i in range(l, r):
rain.append(i)
umb = []
for _ in range(m):
umb.append(iia())
rain.sort()
umb.sort()
dp = [0] * (a + 1)
for i in range(a + 1):
if i not in rain:
if i != 0:
dp[i] = dp[i - 1]
else:
for j in umb:
if j[0] <= i:
temp = (i + 1 - j[0]) * j[1]
if j[0] - 1 >= 0:
temp += dp[j[0] - 1]
if dp[i] > 0:
dp[i] = min(dp[i], temp)
else:
dp[i] = temp
else:
break
# print(dp)
if umb[0][0] > rain[0]:
print(-1)
else:
print(dp[-1])
``` | output | 1 | 102,674 | 24 | 205,349 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.