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.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. | instruction | 0 | 29,390 | 24 | 58,780 |
Tags: brute force, dp
Correct Solution:
```
n, a,b,c = map(int, input().split())
z = [0] + [-999999] * 50000
for i in range(1,n+1):
z[i] = max(z[i-a],z[i-b],z[i-c]) + 1
print(z[n])
``` | output | 1 | 29,390 | 24 | 58,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. | instruction | 0 | 29,391 | 24 | 58,782 |
Tags: brute force, dp
Correct Solution:
```
import sys
import math
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
from functools import reduce
sys.setrecursionlimit(10**6)
def inputt():
return sys.stdin.readline().strip()
def printt(n):
sys.stdout.write(str(n)+'\n')
def listt():
return [int(i) for i in inputt().split()]
def gcd(a,b):
return math.gcd(a,b)
def lcm(a,b):
return (a*b) // gcd(a,b)
def factors(n):
step = 2 if n%2 else 1
return set(reduce(list.__add__,([i, n//i] for i in range(1, int(math.sqrt(n))+1, step) if n % i == 0)))
def comb(n,k):
factn=math.factorial(n)
factk=math.factorial(k)
fact=math.factorial(n-k)
ans=factn//(factk*fact)
return ans
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n > 2 and n % 2 == 0:
return False
max_div = math.floor(math.sqrt(n))
for i in range(3, 1 + max_div, 2):
if n % i == 0:
return False
return True
def maxpower(n,x):
B_max = int(math.log(n, x)) + 1#tells upto what power of x n is less than it like 1024->5^4
return B_max
s = input().split()
n = int(s[0])
a = int(s[1])
b = int(s[2])
c = int(s[3])
dp = [-4001 for i in range(4000+1)]
dp[a] = 1
dp[b] = 1
dp[c] = 1
for i in range(n+1):
if i-a >= 0:
dp[i] = max(dp[i],1+dp[i-a])
if i-b >= 0:
dp[i] = max(dp[i],1+dp[i-b])
if i-c >= 0:
dp[i] = max(dp[i],1+dp[i-c])
print(dp[n])
``` | output | 1 | 29,391 | 24 | 58,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. | instruction | 0 | 29,392 | 24 | 58,784 |
Tags: brute force, dp
Correct Solution:
```
n, a, b, c = map(int, input().split())
tmp = [a, b, c]
tmp.sort()
tmp.reverse()
a, b, c = tmp
ans = 0
for x in range(n // a + 1):
for y in range(n // b + 1):
k = n - a * x - b * y
if k < 0 or k % c != 0:
continue
z = k // c
ans = max(ans, x + y + z)
print(ans)
``` | output | 1 | 29,392 | 24 | 58,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. | instruction | 0 | 29,393 | 24 | 58,786 |
Tags: brute force, dp
Correct Solution:
```
n,a,b,c=[int(x) for x in input().split()]
x,y,z=sorted([a,b,c])
L=[]
for i in range(n//z+1):
if i==n/z:
L.append(int(i))
break
else:
for j in range((n-i*z)//y+1):
if j==(n-i*z)/y:
L.append(int(i+j))
break
else:
t=(n-i*z-j*y)/x
if t==int(t):
L.append(int(i+j+t))
break
print(max(L))
``` | output | 1 | 29,393 | 24 | 58,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. | instruction | 0 | 29,394 | 24 | 58,788 |
Tags: brute force, dp
Correct Solution:
```
N,a,b,c = map(int,input().split())
dp = [[0]+[-1e9 for x in range(4002)] for x in range(4)]
def max_ribbon(W, val, n):
# Build table K[][] in bottom up manner
for i in range(1,n + 1):
for w in range(1,W + 1):
if val[i-1] <= w:
dp[i][w] = max(dp[i-1][w], 1 + dp[i][w-val[i-1]])
else:
dp[i][w] = dp[i-1][w]
return dp[n][W]
val = [a,b,c]
print(max_ribbon(N,val,3))
``` | output | 1 | 29,394 | 24 | 58,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. | instruction | 0 | 29,395 | 24 | 58,790 |
Tags: brute force, dp
Correct Solution:
```
inp=list(map(int,input().split()))
n=inp[0]
arr=inp[1:]
t=[[0 for i in range(n+1)] for i in range(4)]
for j in range(n+1):
t[0][j]=float("-inf")
for i in range(1,4):
for j in range(1,n+1):
if(arr[i-1]<=j):
t[i][j]=max(1+t[i][j-arr[i-1]],t[i-1][j])
else:
t[i][j]=t[i-1][j]
print(t[3][n])
``` | output | 1 | 29,395 | 24 | 58,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. | instruction | 0 | 29,396 | 24 | 58,792 |
Tags: brute force, dp
Correct Solution:
```
n, a, b, c = map(int, input().split())
arr = [0] + [int(-1e7)] * 4200
for i in range(1, n + 1):
arr[i] = max(arr[i - a], arr[i - b], arr[i - c]) + 1
print(arr[n])
``` | output | 1 | 29,396 | 24 | 58,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Submitted Solution:
```
l=list(map(int,input().split()))
n=l[0]
l.pop(0)
l.sort(reverse=True)
a,b,c=l[0],l[1],l[2]
x=0
t=0
for i in range(n//a+1):
for j in range((n-i*a)//b+1):
t=n-i*a-j*b
if t%c==0:
x=max(x,i+j+t//c)
break
print(x)
``` | instruction | 0 | 29,397 | 24 | 58,794 |
Yes | output | 1 | 29,397 | 24 | 58,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000)
n, a, b, c = [int(x) for x in sys.stdin.readline().strip().split()]
dp = [0]*(4002)
dp[-1] = -10**8
for i in range(1,n+1):
dp[i] = max(dp[i-a if i-a>=0 else -1]+1,dp[i-b if i-b>=0 else -1]+1,dp[i-c if i-c>=0 else -1]+1)
print(dp[n])
``` | instruction | 0 | 29,398 | 24 | 58,796 |
Yes | output | 1 | 29,398 | 24 | 58,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Submitted Solution:
```
def Main():
n, a, b, c = map(int, input().split())
dp = [0] * 4001
dp[a] = 1
dp[b] = 1
dp[c] = 1
for i in range(n+1):
if i - a >= 0 and dp[i-a] > 0 and dp[i-a]+1 > dp[i]:
dp[i] = dp[i-a]+1
if i - b >= 0 and dp[i-b] > 0 and dp[i-b]+1 > dp[i]:
dp[i] = dp[i-b]+1
if i - c >= 0 and dp[i-c] > 0 and dp[i-c]+1 > dp[i]:
dp[i] = dp[i-c]+1
print(dp[n])
if __name__ == "__main__":
Main()
``` | instruction | 0 | 29,399 | 24 | 58,798 |
Yes | output | 1 | 29,399 | 24 | 58,799 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Submitted Solution:
```
n,a,b,c=map(int,input().split())
dp=[-10000000000000]*(n+1)
dp[0]=0
for j in [a,b,c]:
for i in range(j,n+1):
dp[i]=max(dp[i],dp[i-j]+1)
print(dp[n])
``` | instruction | 0 | 29,400 | 24 | 58,800 |
Yes | output | 1 | 29,400 | 24 | 58,801 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Submitted Solution:
```
import sys
n, s1, s2, s3 = list(map(int, input().split()))
a = min(s1, s2, s3)
c = max(s1, s2, s3)
b = s1 + s2 + s3 - a - c
r = n % a
f = []
if r == 0:
print(n//a)
else:
for i in range(1, n//a+1):
nn = a*i + r
nr = nn % b
if nr == 0:
print(n // a - i , nn // b)
sys.exit()
for j in range(0, nn//b):
nnn = a*i + r - j * b
nnr = nnn % c
if nnr == 0:
ta = n // a - i
tc = nnn // c
tb = (n - ta * a - tc*c) // b
print(ta, tb , tc)
sys.exit()
``` | instruction | 0 | 29,401 | 24 | 58,802 |
No | output | 1 | 29,401 | 24 | 58,803 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Submitted Solution:
```
n,a,b,c=[int(x) for x in input().split()]
m=0
q=max(a,b,c)
w=min(a,b,c)
e=a+b+c-q-w
c=w;b=e;a=q
ws=0
if n==3999:print(1)
elif n==490 and c==4:print(111)
else :
for i in range(n//a+1):
for j in range(n//b+1):
for k in range(n//c+1):
if i*a+j*b+(n//c-k)*c==n:
m=n//c+i+j-k
ws=1
break
if ws:break
if ws:break
print(m)
``` | instruction | 0 | 29,402 | 24 | 58,804 |
No | output | 1 | 29,402 | 24 | 58,805 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Submitted Solution:
```
n,a,b,c=map(int,input().split())
lst=[a,b,c]
lst.sort()
m=[]
if n==a or n==b or n==c:
m.append(1)
if a+b==n or a+c==n or b+c==n:
m.append(2)
if a+b+c==n:
m.append(3)
if n%lst[0]==0:
m.append((n/lst[0]))
if n%lst[1]==0:
m.append((n/lst[1]))
if n%lst[2]==0:
m.append((n/lst[2]))
if n%lst[0]!=0:
c=n-int(n/lst[0])*lst[0]
if c==lst[1]:
m.append((n//lst[0]+1))
elif c%lst[1]==0:
m.append((n//lst[0]+c//lst[1]))
else:
c1=c-int(n/lst[1])*lst[1]
if c1==lst[2]:
m.append((n//lst[0]+c//lst[1]+1))
elif c1%lst[2]==0:
m.append((n//lst[0]+c//lst[1]+c1//lst[2]))
if c==lst[2]:
m.append((n//lst[0]+1))
elif c%lst[2]==0:
m.append((n//lst[0]+c//lst[2]))
else:
c1=c-int(n/lst[2])*lst[2]
if c1==lst[1]:
m.append((n//lst[0]+c//lst[2]+1))
elif c1%lst[1]==0:
m.append((n//lst[0]+c//lst[2]+c1//lst[1]))
if n%lst[1]!=0:
c=n-int(n/lst[1])*lst[1]
if c==lst[0]:
m.append((n//lst[1]+1))
elif c%lst[0]==0:
m.append((n//lst[1]+c//lst[0]))
else:
c1=c-int(n/lst[0])*lst[0]
if c1==lst[2]:
m.append((n//lst[1]+c//lst[0]+1))
elif c1%lst[2]==0:
m.append((n//lst[1]+c//lst[0]+c1//lst[2]))
if c==lst[2]:
m.append((n//lst[1]+1))
elif c%lst[2]==0:
m.append((n//lst[1]+c//lst[2]))
else:
c1=c-int(n/lst[2])*lst[2]
if c1==lst[0]:
m.append((n//lst[1]+c//lst[2]+1))
elif c1%lst[0]==0:
m.append((n//lst[1]+c//lst[2]+c1//lst[0]))
if n%lst[2]!=0:
c=n-int(n/lst[2])*lst[2]
if c==lst[0]:
m.append((n//lst[2]+1))
elif c%lst[0]==0:
m.append((n//lst[2]+c//lst[0]))
else:
c1=c-int(n/lst[0])*lst[0]
if c1==lst[1]:
m.append((n//lst[2]+c//lst[0]+1))
elif c1%lst[1]==0:
m.append((n//lst[2]+c//lst[0]+c1//lst[1]))
if c==lst[1]:
m.append((n//lst[2]+1))
elif c%lst[1]==0:
m.append((n//lst[2]+c//lst[1]))
else:
c1=c-int(n/lst[1])*lst[1]
if c1==lst[0]:
m.append((n//lst[2]+c//lst[1]+1))
elif c1%lst[0]==0:
m.append((n//lst[2]+c//lst[1]+c1//lst[0]))
if n==4000 and a==3 and b==4:
print(1333)
else:
print(int(max(m)))
``` | instruction | 0 | 29,403 | 24 | 58,806 |
No | output | 1 | 29,403 | 24 | 58,807 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 β€ n, a, b, c β€ 4000) β the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number β the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Submitted Solution:
```
if __name__ == '__main__':
n, a, b, c = [int(x) for x in input().split()]
dp = [0] * (n+1)
for i in range(1, n + 1):
x, y, z = -1, -1, -1
if x == -1 and y == -1 and z == -1:
dp[i] = -1
else:
dp[i] = max(max(y, z), x) + 1
if i >= a:
x = dp[i - a]
if i >= b:
y = dp[i - b]
if i >= c:
z = dp[i - c]
print(dp[n])
``` | instruction | 0 | 29,404 | 24 | 58,808 |
No | output | 1 | 29,404 | 24 | 58,809 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of n computers and m cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with n nodes and m edges. Let's index the computers with integers from 1 to n, let's index the cables with integers from 1 to m.
Polycarpus was given an important task β check the reliability of his company's network. For that Polycarpus decided to carry out a series of k experiments on the computer network, where the i-th experiment goes as follows:
1. Temporarily disconnect the cables with indexes from li to ri, inclusive (the other cables remain connected).
2. Count the number of connected components in the graph that is defining the computer network at that moment.
3. Re-connect the disconnected cables with indexes from li to ri (that is, restore the initial network).
Help Polycarpus carry out all experiments and for each print the number of connected components in the graph that defines the computer network through the given experiment. Isolated vertex should be counted as single component.
Input
The first line contains two space-separated integers n, m (2 β€ n β€ 500; 1 β€ m β€ 104) β the number of computers and the number of cables, correspondingly.
The following m lines contain the cables' description. The i-th line contains space-separated pair of integers xi, yi (1 β€ xi, yi β€ n; xi β yi) β the numbers of the computers that are connected by the i-th cable. Note that a pair of computers can be connected by multiple cables.
The next line contains integer k (1 β€ k β€ 2Β·104) β the number of experiments. Next k lines contain the experiments' descriptions. The i-th line contains space-separated integers li, ri (1 β€ li β€ ri β€ m) β the numbers of the cables that Polycarpus disconnects during the i-th experiment.
Output
Print k numbers, the i-th number represents the number of connected components of the graph that defines the computer network during the i-th experiment.
Examples
Input
6 5
1 2
5 4
2 3
3 1
3 6
6
1 3
2 5
1 5
5 5
2 4
3 3
Output
4
5
6
3
4
2
Submitted Solution:
```
def dsearch(start_point, used_nodes, cycle, matrix):
used_nodes[start_point] = False
connected = matrix[start_point]
for index, node in enumerate(connected):
if node and used_nodes[index]:
used_nodes[index] = False
cycle.append(index)
dsearch(index, used_nodes, cycle, matrix)
n, m = (int(x) for x in input().split())
matrix = [[0] * n for i in range(n)]
used_nodes = [True for i in range(n)]
cycles = []
for i in range(m):
a, b = (int(x) - 1 for x in input().split())
matrix[b][a] = 1
matrix[a][b] = 1
for index, node in enumerate(used_nodes):
if node:
cycle = [index]
dsearch(index, used_nodes, cycle, matrix)
cycles.append(cycle)
print(len(cycles))
for c in cycles:
print(len(c))
for i in c:
print(i + 1, end=' ')
print()
``` | instruction | 0 | 30,386 | 24 | 60,772 |
No | output | 1 | 30,386 | 24 | 60,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved β M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 β€ n, M β€ 20 000, 1 β€ T β€ 86400) β the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R β the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 β from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 β from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.) | instruction | 0 | 31,358 | 24 | 62,716 |
Tags: greedy, two pointers
Correct Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
[p,count,sim] = [1,0,0]
is_solution_there=False
for i in range(1,n+1):
while p<i and a[i] - t + 1>a[p]:
p+=1
if b[p]!=b[p-1]:
sim = max(sim-1,0)
if a[i]<a[p]+t and sim<m:
count+=1
sim+=1
if sim==m:
is_solution_there=True
b[i] = count
if is_solution_there==False:
print("No solution")
return
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
``` | output | 1 | 31,358 | 24 | 62,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved β M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 β€ n, M β€ 20 000, 1 β€ T β€ 86400) β the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R β the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 β from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 β from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.) | instruction | 0 | 31,359 | 24 | 62,718 |
Tags: greedy, two pointers
Correct Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
[a,b]=[[0]*20002,[0]*20002]
if n<m:
print("No solution")
return
for i in range(1,n+1):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
[p,count,sim,ist] = [1,0,0,False]
for i in range(1,n+1):
while p<i and a[i] - t + 1>a[p]:
p+=1
if b[p]!=b[p-1]:
sim = max(sim-1,0)
if a[i]<a[p]+t and sim<m:
[count,sim] = [count+1,sim+1]
if sim==m:
ist=True
b[i] = count
if ist==False:
print("No solution")
return
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
``` | output | 1 | 31,359 | 24 | 62,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved β M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 β€ n, M β€ 20 000, 1 β€ T β€ 86400) β the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R β the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 β from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 β from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
[p,count,sim] = [1,0,0]
is_solution_there=False
for i in range(1,n+1):
while p<i and a[i] - t + 1>a[p]:
p+=1
if b[p]!=b[p-1]:
sim = max(sim-1,1)
if a[i]<a[p]+t and sim<m:
count+=1
sim+=1
if sim==m:
is_solution_there=True
b[i] = count
if is_solution_there==False:
print("No solution")
return
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
``` | instruction | 0 | 31,360 | 24 | 62,720 |
No | output | 1 | 31,360 | 24 | 62,721 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved β M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 β€ n, M β€ 20 000, 1 β€ T β€ 86400) β the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R β the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 β from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 β from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(n):
g = gets()
temp = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
a[i] = temp
[p,count,k,sim] = [0,0,0,0]
for i in range(n):
while p<i and a[i] - t + 1>=a[p]:
p+=1
sim = min(sim,m,i-p+1)
#print(p,a[p],a[i],a[i] - a[p],sim,i-p)
if p==i or (a[i] - t +1<a[p] and sim<m):
count+=1
b[k] = count
sim+=1
else:
b[k] = count
k+=1
print(count)
for i in range(20002):
if b[i] == 0:
break
print(b[i])
if mode=="file":f.close()
if __name__=="__main__":
main()
``` | instruction | 0 | 31,361 | 24 | 62,722 |
No | output | 1 | 31,361 | 24 | 62,723 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved β M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 β€ n, M β€ 20 000, 1 β€ T β€ 86400) β the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R β the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 β from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 β from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
temp = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
a[i] = temp
#print(a[i])
[p,count,sim] = [1,0,0]
for i in range(1,n+1):
while p<i and a[i] - t + 1>=a[p]:
p+=1
#print("Dec",end=' ')
if b[p]!=b[p-1]:
#print("yes")
sim = max(sim-1,0)
#print(p,a[p],a[i],a[i] - a[p],sim,i-p)
if a[i] not in [82126,13978] and (i==p or (a[i] - t +1<a[p] and sim<m)):
count+=1
b[i] = count
sim+=1
else:
b[i] = count
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
``` | instruction | 0 | 31,362 | 24 | 62,724 |
No | output | 1 | 31,362 | 24 | 62,725 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved β M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 β€ n, M β€ 20 000, 1 β€ T β€ 86400) β the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R β the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 β from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 β from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
#print(a[i])
[p,count,sim] = [1,0,0]
for i in range(1,n+1):
while p<i and a[i] - t + 1>=a[p]:
p+=1
if b[p]!=b[p-1]:
#print("yes")
sim = max(sim-1,0)
#print(p,a[p],a[i],a[i] - a[p],sim,i-p)
if a[i]<a[p]+t and sim<m:
count+=1
sim+=1
b[i] = count
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
``` | instruction | 0 | 31,363 | 24 | 62,726 |
No | output | 1 | 31,363 | 24 | 62,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3] | instruction | 0 | 31,868 | 24 | 63,736 |
Tags: data structures
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
class BIT:
def __init__(self, n):
self.btree = [0]*(n+1)
self.n = n
def lowbit(self, num):
return num & (-num)
def update(self, ind, val):
while ind<self.n+1:
self.btree[ind]+=val
ind+=self.lowbit(ind)
def sum(self, ind):
res = 0
while ind:
res+=self.btree[ind]
ind-=self.lowbit(ind)
return res
# ------------------------------
def main():
n, m = RL()
arr = RLL()
bt = BIT(n+m)
mi = [i for i in range(n+1)]
ma = [i for i in range(n+1)]
for i in range(1, n+1):
bt.update(m+i, 1)
rec = [i+m for i in range(n+1)]
pos = m
for q in arr:
mi[q] = 1
ma[q] = max(ma[q], bt.sum(rec[q]))
bt.update(pos, 1)
bt.update(rec[q], -1)
rec[q] = pos
pos-=1
for i in range(1, n+1):
ma[i] = max(ma[i], bt.sum(rec[i]))
for i in range(1, n+1):
print(mi[i], ma[i])
if __name__ == "__main__":
main()
``` | output | 1 | 31,868 | 24 | 63,737 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3] | instruction | 0 | 31,869 | 24 | 63,738 |
Tags: data structures
Correct Solution:
```
import io
import os
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, messages):
# Initial mn/mx is their initial positions
ans = [[i, i] for i in range(N)]
friendsList = SortedList()
friendsToTime = {i: i for i in range(N)}
for f, t in friendsToTime.items():
friendsList.add((t, f))
for t, f in enumerate(messages):
index = friendsList.bisect_left((friendsToTime[f], f))
ans[f][1] = max(ans[f][1], index)
friendsList.remove((friendsToTime[f], f))
friendsToTime[f] = -t - 1
friendsList.add((friendsToTime[f], f))
ans[f][0] = min(ans[f][0], 0)
for i, (t, f) in enumerate(friendsList):
ans[f][0] = min(ans[f][0], i)
ans[f][1] = max(ans[f][1], i)
return "\n".join(str(x + 1) + " " + str(y + 1) for x, y in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
messages = [int(x) - 1 for x in input().split()] # 0 indexed
ans = solve(N, M, messages)
print(ans)
``` | output | 1 | 31,869 | 24 | 63,739 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3] | instruction | 0 | 31,870 | 24 | 63,740 |
Tags: data structures
Correct Solution:
```
n, m = map(int, input().split())
a = [int(i) - 1 for i in input().split()]
ans1 = [i + 1 for i in range(n)]
ans2 = [-1 for i in range(n)]
for i in set(a):
ans1[i] = 1
N = 1
while N < n + m: N <<= 1
st = [0 for i in range(N << 1)]
pos = [i + m for i in range(n)]
for i in range(n):
st[i + N + m] = 1
for i in range(N - 1, 0, -1):
st[i] = st[i << 1] + st[i << 1 | 1]
def up(i,v):
i+=N
st[i]=v
i>>=1
while(i>0):
st[i]=st[i<<1]+st[i<<1|1]
i>>=1
def qr(l,r=N):
l+=N
r+=N
add=0
while(l<r):
if l&1:
add+=st[l]
l+=1
if(r&1):
add+=st[r]
r-=1
l>>=1
r>>=1
return add
for j in range(m):
x = a[j]
i = pos[x]
ans2[x] = max(ans2[x], n - qr(i + 1))
up(i, 0)
pos[x] = m - 1 - j
up(pos[x], 1)
for i in range(n):
x = pos[i]
ans2[i] = max(ans2[i], n - qr(x + 1))
for i in range(n):
print(ans1[i], ans2[i])
``` | output | 1 | 31,870 | 24 | 63,741 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3] | instruction | 0 | 31,871 | 24 | 63,742 |
Tags: data structures
Correct Solution:
```
import io
import os
import random
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/Treap.py
# Modified to support bisect_left/bisect_right/__getitem__ like SortedList
class TreapMultiSet(object):
root = 0
size = 0
def __init__(self, data=None):
if data:
data = sorted(data)
self.root = treap_builder(data)
self.size = len(data)
def add(self, key):
self.root = treap_insert(self.root, key)
self.size += 1
def remove(self, key):
self.root = treap_erase(self.root, key)
self.size -= 1
def discard(self, key):
try:
self.remove(key)
except KeyError:
pass
def ceiling(self, key):
x = treap_ceiling(self.root, key)
return treap_keys[x] if x else None
def higher(self, key):
x = treap_higher(self.root, key)
return treap_keys[x] if x else None
def floor(self, key):
x = treap_floor(self.root, key)
return treap_keys[x] if x else None
def lower(self, key):
x = treap_lower(self.root, key)
return treap_keys[x] if x else None
def max(self):
return treap_keys[treap_max(self.root)]
def min(self):
return treap_keys[treap_min(self.root)]
def __len__(self):
return self.size
def __nonzero__(self):
return bool(self.root)
__bool__ = __nonzero__
def __contains__(self, key):
return self.floor(key) == key
def __repr__(self):
return "TreapMultiSet({})".format(list(self))
def __iter__(self):
if not self.root:
return iter([])
out = []
stack = [self.root]
while stack:
node = stack.pop()
if node > 0:
if right_child[node]:
stack.append(right_child[node])
stack.append(~node)
if left_child[node]:
stack.append(left_child[node])
else:
out.append(treap_keys[~node])
return iter(out)
def __getitem__(self, index):
return treap_find_kth(self.root, index)
def bisect_left(self, value):
return treap_bisect_left(self.root, value)
def bisect_right(self, value):
return treap_bisect_right(self.root, value)
class TreapSet(TreapMultiSet):
def add(self, key):
self.root, duplicate = treap_insert_unique(self.root, key)
if not duplicate:
self.size += 1
def __repr__(self):
return "TreapSet({})".format(list(self))
class TreapHashSet(TreapMultiSet):
def __init__(self, data=None):
if data:
self.keys = set(data)
super(TreapHashSet, self).__init__(self.keys)
else:
self.keys = set()
def add(self, key):
if key not in self.keys:
self.keys.add(key)
super(TreapHashSet, self).add(key)
def remove(self, key):
self.keys.remove(key)
super(TreapHashSet, self).remove(key)
def discard(self, key):
if key in self.keys:
self.remove(key)
def __contains__(self, key):
return key in self.keys
def __repr__(self):
return "TreapHashSet({})".format(list(self))
class TreapHashMap(TreapMultiSet):
def __init__(self, data=None):
if data:
self.map = dict(data)
super(TreapHashMap, self).__init__(self.map.keys())
else:
self.map = dict()
def __setitem__(self, key, value):
if key not in self.map:
super(TreapHashMap, self).add(key)
self.map[key] = value
def __getitem__(self, key):
return self.map[key]
def add(self, key):
raise TypeError("add on TreapHashMap")
def get(self, key, default=None):
return self.map.get(key, default=default)
def remove(self, key):
self.map.pop(key)
super(TreapHashMap, self).remove(key)
def discard(self, key):
if key in self.map:
self.remove(key)
def __contains__(self, key):
return key in self.map
def __repr__(self):
return "TreapHashMap({})".format(list(self))
left_child = [0]
right_child = [0]
subtree_size = [0]
treap_keys = [0]
treap_prior = [0.0]
def treap_builder(sorted_data):
"""Build a treap in O(n) time using sorted data"""
def build(begin, end):
if begin == end:
return 0
mid = (begin + end) // 2
root = treap_create_node(sorted_data[mid])
left_child[root] = build(begin, mid)
right_child[root] = build(mid + 1, end)
subtree_size[root] = end - begin
# sift down the priorities
ind = root
while True:
lc = left_child[ind]
rc = right_child[ind]
if lc and treap_prior[lc] > treap_prior[ind]:
if rc and treap_prior[rc] > treap_prior[rc]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
treap_prior[ind], treap_prior[lc] = treap_prior[lc], treap_prior[ind]
ind = lc
elif rc and treap_prior[rc] > treap_prior[ind]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
break
return root
return build(0, len(sorted_data))
def treap_create_node(key):
treap_keys.append(key)
treap_prior.append(random.random())
left_child.append(0)
right_child.append(0)
subtree_size.append(1)
return len(treap_keys) - 1
def treap_split(root, key):
left_pos = right_pos = 0
stack = []
while root:
if key < treap_keys[root]:
left_child[right_pos] = right_pos = root
root = left_child[root]
stack.append(right_pos)
else:
right_child[left_pos] = left_pos = root
root = right_child[root]
stack.append(left_pos)
left, right = right_child[0], left_child[0]
right_child[left_pos] = left_child[right_pos] = right_child[0] = left_child[0] = 0
treap_update(stack)
return left, right
def treap_merge(left, right):
where, pos = left_child, 0
stack = []
while left and right:
if treap_prior[left] > treap_prior[right]:
where[pos] = pos = left
where = right_child
left = right_child[left]
else:
where[pos] = pos = right
where = left_child
right = left_child[right]
stack.append(pos)
where[pos] = left or right
node = left_child[0]
left_child[0] = 0
treap_update(stack)
return node
def treap_insert(root, key):
if not root:
return treap_create_node(key)
left, right = treap_split(root, key)
return treap_merge(treap_merge(left, treap_create_node(key)), right)
def treap_insert_unique(root, key):
if not root:
return treap_create_node(key), False
left, right = treap_split(root, key)
if left and treap_keys[left] == key:
return treap_merge(left, right), True
return treap_merge(treap_merge(left, treap_create_node(key)), right), False
def treap_erase(root, key):
if not root:
raise KeyError(key)
if treap_keys[root] == key:
return treap_merge(left_child[root], right_child[root])
node = root
stack = [root]
while root and treap_keys[root] != key:
parent = root
root = left_child[root] if key < treap_keys[root] else right_child[root]
stack.append(root)
if not root:
raise KeyError(key)
if root == left_child[parent]:
left_child[parent] = treap_merge(left_child[root], right_child[root])
else:
right_child[parent] = treap_merge(left_child[root], right_child[root])
treap_update(stack)
return node
def treap_ceiling(root, key):
while root and treap_keys[root] < key:
root = right_child[root]
if not root:
return 0
min_node = root
min_key = treap_keys[root]
while root:
if treap_keys[root] < key:
root = right_child[root]
else:
if treap_keys[root] < min_key:
min_key = treap_keys[root]
min_node = root
root = left_child[root]
return min_node
def treap_higher(root, key):
while root and treap_keys[root] <= key:
root = right_child[root]
if not root:
return 0
min_node = root
min_key = treap_keys[root]
while root:
if treap_keys[root] <= key:
root = right_child[root]
else:
if treap_keys[root] < min_key:
min_key = treap_keys[root]
min_node = root
root = left_child[root]
return min_node
def treap_floor(root, key):
while root and treap_keys[root] > key:
root = left_child[root]
if not root:
return 0
max_node = root
max_key = treap_keys[root]
while root:
if treap_keys[root] > key:
root = left_child[root]
else:
if treap_keys[root] > max_key:
max_key = treap_keys[root]
max_node = root
root = right_child[root]
return max_node
def treap_lower(root, key):
while root and treap_keys[root] >= key:
root = left_child[root]
if not root:
return 0
max_node = root
max_key = treap_keys[root]
while root:
if treap_keys[root] >= key:
root = left_child[root]
else:
if treap_keys[root] > max_key:
max_key = treap_keys[root]
max_node = root
root = right_child[root]
return max_node
def treap_min(root):
if not root:
raise ValueError("min on empty treap")
while left_child[root]:
root = left_child[root]
return root
def treap_max(root):
if not root:
raise ValueError("max on empty treap")
while right_child[root]:
root = right_child[root]
return root
def treap_update(path):
for node in reversed(path):
assert node != 0 # ensure subtree_size[nullptr] == 0
lc = left_child[node]
rc = right_child[node]
subtree_size[node] = subtree_size[lc] + 1 + subtree_size[rc]
def treap_find_kth(root, k):
if not root or not (0 <= k < subtree_size[root]):
raise IndexError("treap index out of range")
while True:
lc = left_child[root]
left_size = subtree_size[lc]
if k < left_size:
root = lc
continue
k -= left_size
if k == 0:
return treap_keys[root]
k -= 1
rc = right_child[root]
# assert k < subtree_size[rc]
root = rc
def treap_bisect_left(root, key):
index = 0
while root:
if treap_keys[root] < key:
index += subtree_size[left_child[root]] + 1
root = right_child[root]
else:
root = left_child[root]
return index
def treap_bisect_right(root, key):
index = 0
while root:
if treap_keys[root] <= key:
index += subtree_size[left_child[root]] + 1
root = right_child[root]
else:
root = left_child[root]
return index
# End treap copy and paste
def solve(N, M, messages):
# Initial mn/mx is their initial positions
ans = [[i, i] for i in range(N)]
#friendsList = SortedList()
friendsList = TreapMultiSet()
friendsToTime = {i: i for i in range(N)}
for f, t in friendsToTime.items():
friendsList.add((t, f))
for t, f in enumerate(messages):
index = friendsList.bisect_left((friendsToTime[f], f))
ans[f][1] = max(ans[f][1], index)
friendsList.remove((friendsToTime[f], f))
friendsToTime[f] = -t - 1
friendsList.add((friendsToTime[f], f))
ans[f][0] = min(ans[f][0], 0)
for i, (t, f) in enumerate(friendsList):
ans[f][0] = min(ans[f][0], i)
ans[f][1] = max(ans[f][1], i)
return "\n".join(str(x + 1) + " " + str(y + 1) for x, y in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
messages = [int(x) - 1 for x in input().split()] # 0 indexed
ans = solve(N, M, messages)
print(ans)
``` | output | 1 | 31,871 | 24 | 63,743 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3] | instruction | 0 | 31,872 | 24 | 63,744 |
Tags: data structures
Correct Solution:
```
from sys import stdin, stdout
def update(bita, pos, v):
while pos < len(bita):
bita[pos] += v
pos += lowbit(pos)
def query(bita, pos):
res = 0
while pos > 0:
res += bita[pos]
pos -= lowbit(pos)
return res
def lowbit(p):
return p&(-p)
def getminmax(n, m, ma):
bita = [0]*(n+m+1)
minmax = [[0,0] for i in range(n+1)]
pos = [0]*(n+1)
for i in range(1, n+1):
update(bita, n+1-i, 1)
minmax[i][0] = i
minmax[i][1] = i
pos[i] = n+1-i
#print(bita)
#print(query(bita, n+m))
for i in range(n+1, n+1+m):
mes = ma[i-n-1]
minmax[mes][0] = 1
minmax[mes][1] = max(minmax[mes][1], n - query(bita, pos[mes]-1))
update(bita, pos[mes], -1)
pos[mes] = i
update(bita, pos[mes], 1)
#print(bita)
#print(pos)
for i in range(1, n + 1):
minmax[i][1] = max(minmax[i][1], n - query(bita, pos[i] - 1))
return minmax
if __name__ == '__main__':
nm = list(map(int, stdin.readline().split()))
n = nm[0]
m = nm[1]
ma = list(map(int, stdin.readline().split()))
minmax = getminmax(n,m, ma)
for i in range(1, n+1):
stdout.write(str(minmax[i][0]) + ' ' + str(minmax[i][1]) + '\n')
``` | output | 1 | 31,872 | 24 | 63,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3] | instruction | 0 | 31,873 | 24 | 63,746 |
Tags: data structures
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
class FastIntregral:
def __init__(self, n, *args, **kwargs):
self.mData = [0 for i in range(n+1)]
self.mSize = n
def upd(self, index , value):
while index <= self.mSize:
self.mData[index] += value
index += index & -index
def s(self, index ):
res = 0
while index > 0:
res += self.mData[index]
index -= index & -index
return res
n , m = [int(i) for i in input().split()]
T = FastIntregral( m + n + 1 )
idx = [i + m for i in range(n+1)]
ans_min = [False for i in range(n+1)]
ans_max = [i for i in range(n+1)]
for i in range(m+1 , n + m + 2): T.upd(i,1)
for q in [int(i) for i in input().split()]:
ans_min[q] = True
ans_max[q] = max(ans_max[q] , T.s(idx[q]))
T.upd(idx[q],-1) ; T.upd(m,1)
idx[q] = m ; m -= 1
for i in range(1,n+1):
print(("1" if ans_min[i] else str(i)) + " " + str(max(ans_max[i],T.s(idx[i]))))
``` | output | 1 | 31,873 | 24 | 63,747 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3] | instruction | 0 | 31,874 | 24 | 63,748 |
Tags: data structures
Correct Solution:
```
from __future__ import division, print_function
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
alphabets = list('abcdefghijklmnopqrstuvwxyz')
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def main():
n,m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
minans = [3*100000]*(n+1)
maxans = [0]*(n+1)
s = SortedList()
prev = [(1e7)]*(n+1)
cur = 1e7
for i in range(1,n+1):
s.add((cur,i))
for i in a:
minans[i]=1
element = (prev[i],i)
pos = s.bisect_left(element)
maxans[i]=max(maxans[i],pos+1)
s.remove(element)
cur-=1
prev[i]=cur
s.add((cur,i))
for i in range(1,n+1):
element = s[i-1][1]
minans[element]=min(minans[element],i,element)
maxans[element]=max(maxans[element],i)
for i in range(1,n+1):
print(minans[i],maxans[i])
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | output | 1 | 31,874 | 24 | 63,749 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3] | instruction | 0 | 31,875 | 24 | 63,750 |
Tags: data structures
Correct Solution:
```
import io
import os
import random
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/Treap.py
# Modified to support bisect_left/bisect_right/__getitem__ like SortedList
class TreapMultiSet(object):
root = 0
size = 0
def __init__(self, data=None):
if data:
data = sorted(data)
self.root = treap_builder(data)
self.size = len(data)
def add(self, key):
self.root = treap_insert(self.root, key)
self.size += 1
def remove(self, key):
self.root = treap_erase(self.root, key)
self.size -= 1
def discard(self, key):
try:
self.remove(key)
except KeyError:
pass
def ceiling(self, key):
x = treap_ceiling(self.root, key)
return treap_keys[x] if x else None
def higher(self, key):
x = treap_higher(self.root, key)
return treap_keys[x] if x else None
def floor(self, key):
x = treap_floor(self.root, key)
return treap_keys[x] if x else None
def lower(self, key):
x = treap_lower(self.root, key)
return treap_keys[x] if x else None
def max(self):
return treap_keys[treap_max(self.root)]
def min(self):
return treap_keys[treap_min(self.root)]
def __len__(self):
return self.size
def __nonzero__(self):
return bool(self.root)
__bool__ = __nonzero__
def __contains__(self, key):
return self.floor(key) == key
def __repr__(self):
return "TreapMultiSet({})".format(list(self))
def __iter__(self):
if not self.root:
return iter([])
out = []
stack = [self.root]
while stack:
node = stack.pop()
if node > 0:
if right_child[node]:
stack.append(right_child[node])
stack.append(~node)
if left_child[node]:
stack.append(left_child[node])
else:
out.append(treap_keys[~node])
return iter(out)
def __getitem__(self, index):
return treap_find_kth(self.root, index)
def bisect_left(self, value):
return treap_bisect_left(self.root, value)
def bisect_right(self, value):
return treap_bisect_right(self.root, value)
class TreapSet(TreapMultiSet):
def add(self, key):
self.root, duplicate = treap_insert_unique(self.root, key)
if not duplicate:
self.size += 1
def __repr__(self):
return "TreapSet({})".format(list(self))
class TreapHashSet(TreapMultiSet):
def __init__(self, data=None):
if data:
self.keys = set(data)
super(TreapHashSet, self).__init__(self.keys)
else:
self.keys = set()
def add(self, key):
if key not in self.keys:
self.keys.add(key)
super(TreapHashSet, self).add(key)
def remove(self, key):
self.keys.remove(key)
super(TreapHashSet, self).remove(key)
def discard(self, key):
if key in self.keys:
self.remove(key)
def __contains__(self, key):
return key in self.keys
def __repr__(self):
return "TreapHashSet({})".format(list(self))
class TreapHashMap(TreapMultiSet):
def __init__(self, data=None):
if data:
self.map = dict(data)
super(TreapHashMap, self).__init__(self.map.keys())
else:
self.map = dict()
def __setitem__(self, key, value):
if key not in self.map:
super(TreapHashMap, self).add(key)
self.map[key] = value
def __getitem__(self, key):
return self.map[key]
def add(self, key):
raise TypeError("add on TreapHashMap")
def get(self, key, default=None):
return self.map.get(key, default=default)
def remove(self, key):
self.map.pop(key)
super(TreapHashMap, self).remove(key)
def discard(self, key):
if key in self.map:
self.remove(key)
def __contains__(self, key):
return key in self.map
def __repr__(self):
return "TreapHashMap({})".format(list(self))
left_child = [0]
right_child = [0]
subtree_size = [0]
treap_keys = [0]
treap_prior = [0.0]
def treap_builder(sorted_data):
"""Build a treap in O(n) time using sorted data"""
def build(begin, end):
if begin == end:
return 0
mid = (begin + end) // 2
root = treap_create_node(sorted_data[mid])
left_child[root] = build(begin, mid)
right_child[root] = build(mid + 1, end)
subtree_size[root] = end - begin
# sift down the priorities
ind = root
while True:
lc = left_child[ind]
rc = right_child[ind]
if lc and treap_prior[lc] > treap_prior[ind]:
if rc and treap_prior[rc] > treap_prior[rc]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
treap_prior[ind], treap_prior[lc] = treap_prior[lc], treap_prior[ind]
ind = lc
elif rc and treap_prior[rc] > treap_prior[ind]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
break
return root
return build(0, len(sorted_data))
def treap_create_node(key):
treap_keys.append(key)
treap_prior.append(random.random())
left_child.append(0)
right_child.append(0)
subtree_size.append(1)
return len(treap_keys) - 1
def treap_split(root, key):
left_pos = right_pos = 0
stack = []
while root:
if key < treap_keys[root]:
stack.append(right_pos)
left_child[right_pos] = right_pos = root
root = left_child[root]
else:
stack.append(left_pos)
right_child[left_pos] = left_pos = root
root = right_child[root]
left, right = right_child[0], left_child[0]
stack.append(left_pos)
stack.append(right_pos)
right_child[left_pos] = left_child[right_pos] = right_child[0] = left_child[0] = 0
treap_update_size(stack)
check_size_invariant(left)
check_size_invariant(right)
return left, right
def treap_merge(left, right):
where, pos = left_child, 0
stack = [pos]
while left and right:
if treap_prior[left] > treap_prior[right]:
where[pos] = pos = left
where = right_child
left = right_child[left]
else:
where[pos] = pos = right
where = left_child
right = left_child[right]
stack.append(pos)
where[pos] = left or right
node = left_child[0]
left_child[0] = 0
treap_update_size(stack)
check_size_invariant(node)
return node
def treap_insert(root, key):
if not root:
return treap_create_node(key)
left, right = treap_split(root, key)
return treap_merge(treap_merge(left, treap_create_node(key)), right)
def treap_insert_unique(root, key):
if not root:
return treap_create_node(key), False
left, right = treap_split(root, key)
if left and treap_keys[left] == key:
return treap_merge(left, right), True
return treap_merge(treap_merge(left, treap_create_node(key)), right), False
def treap_erase(root, key):
if not root:
raise KeyError(key)
if treap_keys[root] == key:
return treap_merge(left_child[root], right_child[root])
node = root
stack = [root]
while root and treap_keys[root] != key:
parent = root
root = left_child[root] if key < treap_keys[root] else right_child[root]
stack.append(root)
if not root:
raise KeyError(key)
if root == left_child[parent]:
left_child[parent] = treap_merge(left_child[root], right_child[root])
else:
right_child[parent] = treap_merge(left_child[root], right_child[root])
treap_update_size(stack)
check_size_invariant(node)
return node
def treap_ceiling(root, key):
while root and treap_keys[root] < key:
root = right_child[root]
if not root:
return 0
min_node = root
min_key = treap_keys[root]
while root:
if treap_keys[root] < key:
root = right_child[root]
else:
if treap_keys[root] < min_key:
min_key = treap_keys[root]
min_node = root
root = left_child[root]
return min_node
def treap_higher(root, key):
while root and treap_keys[root] <= key:
root = right_child[root]
if not root:
return 0
min_node = root
min_key = treap_keys[root]
while root:
if treap_keys[root] <= key:
root = right_child[root]
else:
if treap_keys[root] < min_key:
min_key = treap_keys[root]
min_node = root
root = left_child[root]
return min_node
def treap_floor(root, key):
while root and treap_keys[root] > key:
root = left_child[root]
if not root:
return 0
max_node = root
max_key = treap_keys[root]
while root:
if treap_keys[root] > key:
root = left_child[root]
else:
if treap_keys[root] > max_key:
max_key = treap_keys[root]
max_node = root
root = right_child[root]
return max_node
def treap_lower(root, key):
while root and treap_keys[root] >= key:
root = left_child[root]
if not root:
return 0
max_node = root
max_key = treap_keys[root]
while root:
if treap_keys[root] >= key:
root = left_child[root]
else:
if treap_keys[root] > max_key:
max_key = treap_keys[root]
max_node = root
root = right_child[root]
return max_node
def treap_min(root):
if not root:
raise ValueError("min on empty treap")
while left_child[root]:
root = left_child[root]
return root
def treap_max(root):
if not root:
raise ValueError("max on empty treap")
while right_child[root]:
root = right_child[root]
return root
def treap_update_size(path):
for pos in reversed(path):
lc = left_child[pos]
rc = right_child[pos]
left_size = subtree_size[lc] if lc else 0
right_size = subtree_size[rc] if rc else 0
subtree_size[pos] = left_size + 1 + right_size
def check_size_invariant(node):
return
if node == 0:
return 0
lc = left_child[node]
rc = right_child[node]
left_size = subtree_size[lc] if lc else 0
right_size = subtree_size[rc] if rc else 0
assert subtree_size[node] == left_size + 1 + right_size
check_size_invariant(lc)
check_size_invariant(rc)
def treap_find_kth(root, k):
if not root or not (0 <= k < subtree_size[root]):
raise IndexError("treap index out of range")
while True:
lc = left_child[root]
if lc:
if k < subtree_size[lc]:
root = lc
continue
k -= subtree_size[lc]
if k == 0:
return treap_keys[root]
k -= 1
rc = right_child[root]
assert rc and k < subtree_size[rc]
root = rc
def treap_bisect_left(root, key):
index = 0
while root:
if treap_keys[root] < key:
lc = left_child[root]
left_size = subtree_size[lc] if lc else 0
index += left_size + 1
root = right_child[root]
else:
root = left_child[root]
return index
def treap_bisect_right(root, key):
index = 0
while root:
if treap_keys[root] <= key:
lc = left_child[root]
left_size = subtree_size[lc] if lc else 0
index += left_size + 1
root = right_child[root]
else:
root = left_child[root]
return index
# End treap copy and paste
def solve(N, M, messages):
# Initial mn/mx is their initial positions
ans = [[i, i] for i in range(N)]
#friendsList = SortedList()
friendsList = TreapMultiSet()
friendsToTime = {i: i for i in range(N)}
for f, t in friendsToTime.items():
friendsList.add((t, f))
for t, f in enumerate(messages):
index = friendsList.bisect_left((friendsToTime[f], f))
ans[f][1] = max(ans[f][1], index)
friendsList.remove((friendsToTime[f], f))
friendsToTime[f] = -t - 1
friendsList.add((friendsToTime[f], f))
ans[f][0] = min(ans[f][0], 0)
for i, (t, f) in enumerate(friendsList):
ans[f][0] = min(ans[f][0], i)
ans[f][1] = max(ans[f][1], i)
return "\n".join(str(x + 1) + " " + str(y + 1) for x, y in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
messages = [int(x) - 1 for x in input().split()] # 0 indexed
ans = solve(N, M, messages)
print(ans)
``` | output | 1 | 31,875 | 24 | 63,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.buffer.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = int(1e9)+7
def update(v, w):
while v <= N:
BIT[v] += w
v += (v & (-v))
def getvalue(v):
ANS = 0
while v != 0:
ANS += BIT[v]
v -= (v & (-v))
return ANS
def bisect_on_BIT(x):
if x <= 0:
return 0
ANS = 0
h = 1 << (n - 1)
while h > 0:
if ANS + h <= n and BIT[ANS + h] < x:
x -= BIT[ANS + h]
ANS += h
h //= 2
return ANS + 1
n,m=mdata()
a=mdata()
BIT = [0]*(n+m+1)
N=n+m
pos=[0]*(n+1)
v=[0]*(n+1)
for i in range(1,n+1):
pos[i]=n-i+1
v[i]=i
update(i,1)
for i in range(m):
v[a[i]]=max(v[a[i]],getvalue(n+i)-getvalue(pos[a[i]])+1)
update(pos[a[i]],-1)
pos[a[i]]=n+i+1
update(pos[a[i]],1)
s=set(a)
for i in range(1,n+1):
v[i] = max(v[i], getvalue(n + m) - getvalue(pos[i]) + 1)
if i in s:
print(1,v[i])
else:
print(i,v[i])
``` | instruction | 0 | 31,876 | 24 | 63,752 |
Yes | output | 1 | 31,876 | 24 | 63,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from 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=2**30, 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.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n,m=map(int,input().split())
l=list(map(int,input().split()))
se=set(l)
mi=[0]*(n+1)
ma=[0]*(n+1)
pos=[i+m-1 for i in range(n+1)]
for i in range(1,n+1):
if i in se:
mi[i]=1
else:
mi[i]=i
a=[0]*m+[1 for i in range(1,n+1)]+[]
t=m-1
s=SegmentTree(a)
for i in range(m):
w=l[i]
ma[l[i]]=max(ma[l[i]],s.query(0,pos[l[i]]))
last=pos[l[i]]
pos[l[i]]=t
t-=1
s.__setitem__(t+1,1)
s.__setitem__(last,0)
a[t+1]=1
a[last]=0
for i in range(1,n+1):
ma[i]=max(ma[i],s.query(0,pos[i]))
print(mi[i],ma[i])
``` | instruction | 0 | 31,877 | 24 | 63,754 |
Yes | output | 1 | 31,877 | 24 | 63,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
n,m = [int(i) for i in input().split()]
a = [int(i)-1 for i in input().split()]
mini = [i for i in range (1,n+1)]
maxi = [i for i in range (1,n+1)]
for i in a:
mini[i] = 1
s = SortedList()
curr = 100000
for i in range (n):
s.add((curr, i))
prev = [100000] * n
for i in a:
ele = (prev[i], i)
ind = s.bisect_left(ele)
maxi[i] = max(maxi[i], ind+1)
s.remove(ele)
curr-=1
s.add((curr, i))
prev[i] = curr
for i in range (n):
curr = s[i][1]
maxi[curr] = max(maxi[curr], i+1)
maxi[s[-1][1]] = n
for i in range (n):
print(mini[i], maxi[i])
``` | instruction | 0 | 31,878 | 24 | 63,756 |
Yes | output | 1 | 31,878 | 24 | 63,757 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
# SortedList copied from: https://github.com/grantjenks/python-sortedcontainers/blob/master/sortedcontainers/sortedlist.py
# Minified with pyminifier to fit codeforce char limit
from __future__ import print_function
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
from collections.abc import Sequence, MutableSequence
except ImportError:
from collections import Sequence, MutableSequence
from functools import wraps
from sys import hexversion
if hexversion < 0x03000000:
from itertools import imap as map
from itertools import izip as zip
try:
from thread import get_ident
except ImportError:
from dummy_thread import get_ident
else:
from functools import reduce
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
def recursive_repr(fillvalue="..."):
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
class SortedList(MutableSequence):
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError("inherit SortedKeyList for key argument")
@property
def key(self):
return None
def _reset(self, load):
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(
values[pos : (pos + _load)] for pos in range(0, len(values), _load)
)
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError("{0!r} not in list".format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError("{0!r} not in list".format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError("{0!r} not in list".format(value))
def _delete(self, pos, idx):
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
pos += self._offset
while pos:
if not pos & 1:
total += _index[pos - 1]
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError("list index out of range")
elif idx >= self._len:
raise IndexError("list index out of range")
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = range(start, stop, step)
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
start_list = _lists[start_pos]
stop_idx = start_idx + stop - start
if len(start_list) >= stop_idx:
return start_list[start_idx:stop_idx]
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1) : stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
indices = range(start, stop, step)
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError("list index out of range")
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
message = "use ``del sl[index]`` and ``sl.add(value)`` instead"
raise NotImplementedError(message)
def __iter__(self):
return chain.from_iterable(self._lists)
def __reversed__(self):
return chain.from_iterable(map(reversed, reversed(self._lists)))
def reverse(self):
raise NotImplementedError("use ``reversed(sl)`` instead")
def islice(self, start=None, stop=None, reverse=False):
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(range(min_idx, max_idx))
return map(_lists[min_pos].__getitem__, indices)
indices = range(min_idx, max_idx)
return map(_lists[min_pos].__getitem__, indices)
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
map(_lists[max_pos].__getitem__, max_indices),
)
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, reversed(sublist_indices))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
chain.from_iterable(map(reversed, sublists)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, sublist_indices)
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
chain.from_iterable(sublists),
map(_lists[max_pos].__getitem__, max_indices),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
return self._len
def bisect_left(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
return self.__class__(self)
__copy__ = copy
def append(self, value):
raise NotImplementedError("use ``sl.add(value)`` instead")
def extend(self, values):
raise NotImplementedError("use ``sl.update(values)`` instead")
def insert(self, index, value):
raise NotImplementedError("use ``sl.add(value)`` instead")
def pop(self, index=-1):
if not self._len:
raise IndexError("pop index out of range")
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError("{0!r} is not in list".format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError("{0!r} is not in list".format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError("{0!r} is not in list".format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError("{0!r} is not in list".format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError("{0!r} is not in list".format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
self._update(other)
return self
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
def comparer(self, other):
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = "__{0}__".format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, "==", "equal to")
__ne__ = __make_cmp(ne, "!=", "not equal to")
__lt__ = __make_cmp(lt, "<", "less than")
__gt__ = __make_cmp(gt, ">", "greater than")
__le__ = __make_cmp(le, "<=", "less than or equal to")
__ge__ = __make_cmp(ge, ">=", "greater than or equal to")
__make_cmp = staticmethod(__make_cmp)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values,))
@recursive_repr()
def __repr__(self):
return "{0}({1!r})".format(type(self).__name__, list(self))
def _check(self):
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
print("len", self._len)
print("load", self._load)
print("offset", self._offset)
print("len_index", len(self._index))
print("index", self._index)
print("len_maxes", len(self._maxes))
print("maxes", self._maxes)
print("len_lists", len(self._lists))
print("lists", self._lists)
raise
def identity(value):
return value
class SortedKeyList(SortedList):
def __init__(self, iterable=None, key=identity):
self._key = key
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
return self._key
def clear(self):
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, value):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(value)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, value)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([value])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > (self._load << 1):
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(
values[pos : (pos + _load)] for pos in range(0, len(values), _load)
)
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == value:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError("{0!r} not in list".format(value))
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError("{0!r} not in list".format(value))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError("{0!r} not in list".format(value))
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError("{0!r} not in list".format(value))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > (self._load >> 1):
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
min_key = self._key(minimum) if minimum is not None else None
max_key = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse,
)
def irange_key(
self, min_key=None, max_key=None, inclusive=(True, True), reverse=False
):
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, value):
return self._bisect_key_left(self._key(value))
def bisect_right(self, value):
return self._bisect_key_right(self._key(value))
bisect = bisect_right
def bisect_key_left(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == value:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
return self.__class__(self, key=self._key)
__copy__ = copy
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError("{0!r} is not in list".format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError("{0!r} is not in list".format(value))
_maxes = self._maxes
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError("{0!r} is not in list".format(value))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError("{0!r} is not in list".format(value))
if _lists[pos][idx] == value:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError("{0!r} is not in list".format(value))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError("{0!r} is not in list".format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values, key=self._key)
__radd__ = __add__
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values, key=self._key)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values, self.key))
@recursive_repr()
def __repr__(self):
type_name = type(self).__name__
return "{0}({1!r}, key={2!r})".format(type_name, list(self), self._key)
def _check(self):
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert self._len == sum(len(sublist) for sublist in self._lists)
for sublist in self._keys:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
for val_sublist, key_sublist in zip(self._lists, self._keys):
assert len(val_sublist) == len(key_sublist)
for val, key in zip(val_sublist, key_sublist):
assert self._key(val) == key
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._keys[pos][-1]
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
print("len", self._len)
print("load", self._load)
print("offset", self._offset)
print("len_index", len(self._index))
print("index", self._index)
print("len_maxes", len(self._maxes))
print("maxes", self._maxes)
print("len_keys", len(self._keys))
print("keys", self._keys)
print("len_lists", len(self._lists))
print("lists", self._lists)
raise
SortedListWithKey = SortedKeyList
# Created by pyminifier (https://github.com/liftoff/pyminifier)
################################ End copy and paste
import io
import os
from collections import Counter, defaultdict, deque
# from sortedcontainers import SortedList
def solve(N, M, messages):
# Initial mn/mx is their initial positions
ans = [[i, i] for i in range(N)]
friendsList = SortedList()
friendsToTime = {i: i for i in range(N)}
for f, t in friendsToTime.items():
friendsList.add((t, f))
for t, f in enumerate(messages):
index = friendsList.bisect_left((friendsToTime[f], f))
ans[f][1] = max(ans[f][1], index)
friendsList.remove((friendsToTime[f], f))
friendsToTime[f] = -t - 1
friendsList.add((friendsToTime[f], f))
ans[f][0] = min(ans[f][0], 0)
for i, (t, f) in enumerate(friendsList):
ans[f][0] = min(ans[f][0], i)
ans[f][1] = max(ans[f][1], i)
return "\n".join(str(x + 1) + " " + str(y + 1) for x, y in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
messages = [int(x) - 1 for x in input().split()] # 0 indexed
ans = solve(N, M, messages)
print(ans)
``` | instruction | 0 | 31,879 | 24 | 63,758 |
Yes | output | 1 | 31,879 | 24 | 63,759 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
nm = list(map(int ,input().split()))
n = nm[0]
m = nm[1]
messages = list(map(int, input().split()))
min_pos = []
max_pos = []
config = []
for item1 in range(n):
min_pos.append(0)
max_pos.append(0)
for item2 in range(n):
config.append(item2 + 1)
for num1 in range(n):
if num1+1 in messages:
min_pos[num1] = 1
else:
min_pos[num1] = config.index(num1+1) + 1
max_pos[num1] = config.index(num1+1) + 1
for num2 in messages:
if num2 == config[0]:
continue
else:
temp = []
temp.append(num2)
config.remove(num2)
config = temp + config
for item in config:
if min_pos[item-1] > config.index(item) + 1:
min_pos[item-1] = config.index(item) + 1
if max_pos[item-1] < config.index(item) + 1:
max_pos[item-1] = config.index(item) + 1
for item in zip(min_pos,max_pos):
print(item)
``` | instruction | 0 | 31,880 | 24 | 63,760 |
No | output | 1 | 31,880 | 24 | 63,761 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import defaultdict
class Bit:
def __init__(self,n):
self.size = n
self.tree = [0]*(n+1)
def sum(self,i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self,i,x):
while i <= self.size:
self.tree[i] += x
i += i & -i
n,m = map(int,input().split())
a = list(map(int,input().split()))
ls = []
if a[0] != 1:
ls.append(a[0])
for i in range(1,m):
if a[i-1] != a[i]:
ls.append(a[i])
m = len(ls)
dc = defaultdict(int)
bit = Bit(n+1)
ansls = [[i,i] for i in range(n+1)]
if m == 0:
for i in range(1,n+1):
print(*ansls[i])
exit()
for i in range(m):
x = ls[i]
if dc[x] == 0:
dc[x] = i+1
ansls[x] = [1,x+bit.sum(n)-bit.sum(x)]
bit.add(x,1)
else:
ansls[x][1] = min(n,max(ansls[x][1],i+1-dc[x]))
dc[x] = i+1
for i in range(1,n+1):
if dc[i] == 0:
ansls[i][1] = min(n,i+bit.sum(n)-bit.sum(i))
else:
ansls[i][1] = min(n,max(ansls[i][1],m+1-dc[i]))
for i in range(1,n+1):
print(*ansls[i])
``` | instruction | 0 | 31,881 | 24 | 63,762 |
No | output | 1 | 31,881 | 24 | 63,763 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
n,m=map(int,input().split())
friends=[[i,i] for i in range(n)]
p=[i for i in range(n)]
s=list(map(int,input().split()))
for i in range(m):
j=s[i]
p.remove(j-1)
p=[j-1]+p
friends[j-1][0]=0
for sb in range(1,j):
if friends[sb][1]<p.index(sb):
friends[sb][1]=p.index(sb)
for i in friends:
print(i[0]+1,i[1]+1)
``` | instruction | 0 | 31,882 | 24 | 63,764 |
No | output | 1 | 31,882 | 24 | 63,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3 β
10^5) β the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ n) β the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
from collections import deque
from bisect import bisect_left
n,m = map(int, input().split())
alist = list(map(int, input().split()))
posmax = {}
moved = []
pos = {}
c = 0
for idx,a in enumerate(alist):
i = bisect_left(moved, a)
if i == c or moved[i] != a:
posmax[a] = a+c-i
moved.insert(i,a)
c+=1
else:
posmax[a] = max(posmax[a], idx-pos[a])
pos[a] = idx
lines = deque()
d = 0
for i in range(n,0,-1):
a,b = i,i
if i in pos:
a,b = 1,max(posmax[i],c-pos[i])
d+=1
else:
b+=d
lines.appendleft("{} {}".format(a,b))
print('\n'.join(lines))
``` | instruction | 0 | 31,883 | 24 | 63,766 |
No | output | 1 | 31,883 | 24 | 63,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1]. | instruction | 0 | 31,952 | 24 | 63,904 |
Tags: implementation, two pointers
Correct Solution:
```
for _ in range (int(input())):
n=int(input())
arr=list(map(int,input().split()[:n]))
arr1=[0]*n
i=0
if n%2!=0:
for j in range (0,n,2):
arr1[j]=arr[i]
i+=1
for k in range (n-2,0,-2):
arr1[k]=arr[i]
i+=1
else:
for j in range (0,n,2):
arr1[j]=arr[i]
i+=1
for k in range (n-1,0,-2):
arr1[k]=arr[i]
i+=1
print(*arr1)
``` | output | 1 | 31,952 | 24 | 63,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1]. | instruction | 0 | 31,953 | 24 | 63,906 |
Tags: implementation, two pointers
Correct Solution:
```
test_cases = int(input())
for i in range(test_cases):
size = int(input())
arr = list(map(int, input().split()))
ans = []
for i in range(size // 2):
ans.append(str(arr[i]))
ans.append(str(arr[size-i-1]))
if size % 2 != 0:
ans = ans + [str(arr[size // 2])]
print(' '.join(ans))
``` | output | 1 | 31,953 | 24 | 63,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1]. | instruction | 0 | 31,954 | 24 | 63,908 |
Tags: implementation, two pointers
Correct Solution:
```
t = int(input())
ans = []
for i in range(t):
n = int(input())
b = input().split()
i = 0
j = len(b) - 1
res = []
while i < j:
res.append(b[i])
res.append(b[j])
i += 1
j -= 1
if i == j:
res.append(b[i])
ans.append(res)
for a in ans:
print(" ".join(a))
``` | output | 1 | 31,954 | 24 | 63,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1]. | instruction | 0 | 31,955 | 24 | 63,910 |
Tags: implementation, two pointers
Correct Solution:
```
from collections import deque
def solution(n, blist):
deq = deque(blist)
ans = []
for i in range(len(blist)):
if i % 2 == 0:
ans.append(deq.popleft())
else:
ans.append(deq.pop())
return ans
t = int(input())
for tt in range(t):
n = int(input())
blist = list(map(int, input().split()))
for num in solution(n, blist):
print(num, end=' ')
print()
``` | output | 1 | 31,955 | 24 | 63,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1]. | instruction | 0 | 31,956 | 24 | 63,912 |
Tags: implementation, two pointers
Correct Solution:
```
t=int(input())
while(t>0):
n=int(input())
arr=list(map(int,input().strip().split()))
l=len(arr)
l1=[]
l2=[]
flag=0
if(l%2!=0):
x=arr[l//2]
flag=1
l1=arr[:l//2]
l2=arr[(l//2)+1:]
else:
l1=arr[:l//2]
l2=arr[l//2:]
l2.reverse()
num=n
j=0
i=0
ans=[0]*n
p=len(l1)
while(p>0):
ans[j]=l1[i]
j+=1
ans[j]=l2[i]
j+=1
i+=1
p-=1
if(flag==1):
ans[j]=x
print(*ans)
t-=1
``` | output | 1 | 31,956 | 24 | 63,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1]. | instruction | 0 | 31,957 | 24 | 63,914 |
Tags: implementation, two pointers
Correct Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
l1=l[::-1]
k=[]
o=0
j=0
for i in range(n):
if(i%2==0):
k.append(l[o])
o+=1
else:
k.append(l1[j])
j+=1
for i in k:
print(i,end=" ")
print()
``` | output | 1 | 31,957 | 24 | 63,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1]. | instruction | 0 | 31,958 | 24 | 63,916 |
Tags: implementation, two pointers
Correct Solution:
```
import math ;
t = int(input());
while(t > 0 ):
t-=1 ;
n = int(input());
a = list(map(int , input().split(' ')))
ans = []
for i in range(int(n/2)):
ans.append(a[i]);
ans.append(a[n-1-i]);
if(n%2 > 0 ):
ans.append(a[math.floor(n/2)])
print((*ans))
``` | output | 1 | 31,958 | 24 | 63,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1]. | instruction | 0 | 31,959 | 24 | 63,918 |
Tags: implementation, two pointers
Correct Solution:
```
n = int(input())
for i in range(n):
t = int(input())
s = input().split()
q = 0
w = t-1
if abs(q-w) == 1:
print(s[q], s[w])
elif len(s) == 1:
print(*s)
else:
while q != w:
print(s[q],s[w],end = ' ')
q+=1
w-=1
if q == w:
print(s[q])
break
elif abs(q-w) == 1:
print(s[q], s[w])
break
``` | output | 1 | 31,959 | 24 | 63,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1].
Submitted Solution:
```
#import numpy as np
#import collections
#import sys
# =============================================================================
def get_primeFactor(n):
res=[1]
x=2
while x*x<=n:
while n%x==0:
res.append(x)
n//=x
x+=1
if n>1:res.append(n)
return res
def getFactor(n):
res={1,n}
x=2
while x*x<=n:
if n%x==0:
res.add(x)
res.add(n//x)
x+=1
return res
def solve():
n=int(input())
arr=list(map(int,input().split()))
if len(arr)<=2:return ' '.join(str(i) for i in arr)
res=''
for i in range((n//2)):
res+='{} '.format(arr[i])
res+='{} '.format(arr[n-i-1])
if n%2==0:return res
else :return res+str(arr[n//2])
for _ in range(int(input())):
print(solve())
``` | instruction | 0 | 31,960 | 24 | 63,920 |
Yes | output | 1 | 31,960 | 24 | 63,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1].
Submitted Solution:
```
t = int(input())
list = []
for i in range(t):
n = int(input())
s = input()
s = s.split(' ')
i = 0
j = -1
n_s = ""
if n % 2 == 0:
while(i+1 <= n//2):
n_s = n_s + s[i] + ' ' + s[j] + ' '
i = i + 1
j = j - 1
n_s = n_s[0:-1]
else:
while(i+1 <= n//2):
n_s = n_s + s[i] + ' ' + s[j] + ' '
i = i + 1
j = j - 1
n_s = n_s + s[i]
list.append(n_s)
for item in list:
print(item)
``` | instruction | 0 | 31,961 | 24 | 63,922 |
Yes | output | 1 | 31,961 | 24 | 63,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1].
Submitted Solution:
```
import math
n=int(input())
for i in range(2*n):
m=input()
p=[]
if i%2==1:
a=m.split()
q=math.ceil(len(a)/2)
x=a[:q]
y=list(a[len(a):q-1:-1])
for j in range(len(a)):
if j%2==0:
p.append(x.pop(0))
elif j%2==1:
p.append(y.pop(0))
print(' '.join(p))
``` | instruction | 0 | 31,962 | 24 | 63,924 |
Yes | output | 1 | 31,962 | 24 | 63,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n β₯ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 β€ t β€ 300) β the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 300) β the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,β¦, b_n (1 β€ b_i β€ 10^9) β the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer β is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] β [3, 1] β [3, 4, 1] β [3, 4, 1, 1] β [3, 4, 5, 1, 1] β [3, 4, 5, 9, 1, 1] β [3, 4, 5, 2, 9, 1, 1].
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
seq=list(map(int, input().split()))
while seq:
print(seq.pop(0), end=' ')
if seq:
print(seq.pop(len(seq)-1), end=' ')
print()
``` | instruction | 0 | 31,963 | 24 | 63,926 |
Yes | output | 1 | 31,963 | 24 | 63,927 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.