text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Tags: constructive algorithms, dp, greedy, implementation
Correct Solution:
```
from __future__ import division, print_function
import os,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
from bisect import bisect_left as lower_bound, bisect_right as upper_bound
def so(): return int(input())
def st(): return input()
def mj(): return map(int,input().strip().split(" "))
def msj(): return map(str,input().strip().split(" "))
def le(): return list(map(int,input().split()))
def lebe():return list(map(int, input()))
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
def joro(L):
return(''.join(map(str, L)))
def decimalToBinary(n): return bin(n).replace("0b","")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def tr(n):
return n*(n+1)//2
def iu():
n,p,q=mj()
L=le()
a,b=p,-p
g=1
for i in range(n):
if(q<L[i]):
g=0
break
a=min(q-L[i],p)
if(a!=p):
b=max(1+b,-a)
else:
b=-q
if(a<b):
g=0
break
if(g==1):
print("Yes")
else:
print("No")
def main():
for i in range(so()):
iu()
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
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__":
#read()
main()
#dmain()
# Comment Read()
```
| 91,100 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Tags: constructive algorithms, dp, greedy, implementation
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def check(k,l,d,st,en):
ad = k-1
for i in range(st+1,en):
if d[i]+abs(ad) <= l:
ad -= 1
else:
if ad <= 0:
return 0
ad = l-d[i]-1
return 1
def solve(n,k,l,d):
stops = [-1]
for ind,i in enumerate(d):
if i+k<=l:
stops.append(ind)
elif i>l:
return 'NO'
stops.append(n)
for i in range(1,len(stops)):
if not check(k,l,d,stops[i-1],stops[i]):
return 'NO'
return 'YES'
def main():
for _ in range(int(input())):
n,k,l = map(int,input().split())
d = list(map(int,input().split()))
print(solve(n,k,l,d))
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
```
| 91,101 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Tags: constructive algorithms, dp, greedy, implementation
Correct Solution:
```
import sys
inpy = [int(x) for x in sys.stdin.read().split()]
t = inpy[0]
index = 1
for _ in range(t):
n, k, l = inpy[index], inpy[index+1], inpy[index+2]
index += 3
d = inpy[index:index+n]
index += n
x, m = k, True
flag = True
for i in range(n):
diff = l - d[i]
if diff < 0:
flag = False
break
if diff >= k:
x = k
m = True
else:
if m:
x = min(x - 1, diff)
if x == 0:
m = False
else:
x = x + 1
if x > diff:
flag = False
break
if flag :
print('Yes')
else:
print('No')
```
| 91,102 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Tags: constructive algorithms, dp, greedy, implementation
Correct Solution:
```
# input = open('file.txt').readline
for _ in range( int(input()) ):
n , k , l = map( int , input().strip().split(" ") )
arr = list(map( int , input().strip().split(" ") ))
goods = []
bad = False
for i , a in enumerate( arr ):
if a + k <= l:
goods.append(i)
if a > l:
bad = True
break
if bad:
print('No')
continue
goods.append(n)
prev = -1
for g in goods:
st = prev
en = g
# print(st , en)
if st + 1 == en:
prev = g
continue
tk = k
while st < en-1 and tk > 0:
st += 1
tk -= 1
plc = arr[st] + tk
if plc > l:
tk -= ( plc - l )
if tk < 0:
bad = True
# print(st, en , tk , 'after')
if tk == 0:
while st < en-1:
st += 1
tk += 1
plc = arr[st] + tk
# print('inside',st,tk,plc)
if plc > l:
bad = True
break
if bad:
break
prev = g
if bad:
print('No')
else:
print('Yes')
```
| 91,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Tags: constructive algorithms, dp, greedy, implementation
Correct Solution:
```
#
# ------------------------------------------------
# ____ _ Generatered using
# / ___| | |
# | | __ _ __| | ___ _ __ ______ _
# | | / _` |/ _` |/ _ \ '_ \|_ / _` |
# | |__| (_| | (_| | __/ | | |/ / (_| |
# \____\____|\____|\___|_| |_/___\____|
#
# GNU Affero General Public License v3.0
# ------------------------------------------------
# Author : prophet
# Created : 2020-07-24 11:19:20.229238
# UUID : dFs0Ek0q78tkOXbf
# ------------------------------------------------
#
production = True
import sys, math, collections
def input(input_format = 0, multi = 0):
if multi > 0: return [input(input_format) for i in range(multi)]
else:
next_line = sys.stdin.readline()[:-1]
if input_format >= 10:
use_list = False
input_format = int(str(input_format)[-1])
else: use_list = True
if input_format == 0: formatted_input = [next_line]
elif input_format == 1: formatted_input = list(map(int, next_line.split()))
elif input_format == 2: formatted_input = list(map(float, next_line.split()))
elif input_format == 3: formatted_input = list(next_line)
elif input_format == 4: formatted_input = list(map(int, list(next_line)))
elif input_format == 5: formatted_input = next_line.split()
else: formatted_input = [next_line]
return formatted_input if use_list else formatted_input[0]
def out(output_line, output_format = 0, newline = True):
formatted_output = ""
if output_format == 0: formatted_output = str(output_line)
elif output_format == 1: formatted_output = " ".join(map(str, output_line))
elif output_format == 2: formatted_output = "\n".join(map(str, output_line))
elif output_format == 3: formatted_output = "".join(map(str, output_line))
print(formatted_output, end = "\n" if newline else "")
def log(*args):
if not production:
print("$$$", end = "")
print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c
ceil = lambda a, b: -(-a // b)
flip = lambda a: (a + 1) & 1
def mapl(iterable, format = 0):
if format == 0: return list(map(int, iterable))
elif format == 1: return list(map(str, iterable))
elif format == 2: return list(map(list, iterable))
#
# >>>>>>>>>>>>>>> START OF SOLUTION <<<<<<<<<<<<<<
#
def solve():
n, k, l = input(1)
d = input(1)
log(k, l)
log(d)
f = [l - i for i in d]
log(f)
p = [(0, 2 * k - 1)]
for i in f:
a, b = p[-1]
if i >= k:
p.append((0, 2 * k - 1))
else:
fb = k + i
fa = max(a + 1, k - i)
log(i, fb, fa)
if fb < fa:
out("No")
return
p.append((fa, fb))
log(p)
else:
out("Yes")
log("")
return
for i in range(input(11)): solve()
#
# >>>>>>>>>>>>>>>> END OF SOLUTION <<<<<<<<<<<<<<<
#
```
| 91,104 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Tags: constructive algorithms, dp, greedy, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n, k, l = map(int, input().split())
d = list(map(int, input().split()))
safe = [0]
for i in range(n):
if d[i]+k<=l:
safe.append(i+1)
safe.append(n+1)
ok = True
for i in range(1, len(safe)):
tide = k
down = True
for j in range(safe[i-1], safe[i]-1):
tide += -1 if down else 1
if down:
tide -= max(0, d[j]+tide-l)
if tide<0 or d[j]+tide>l:
ok = False
break
if tide==0:
down = False
if ok:
print('Yes')
else:
print('No')
```
| 91,105 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Submitted Solution:
```
t=int(input())
for _ in range(t):
n,k,l=[int(x) for x in input().split()]
d=[int(x) for x in input().split()]
for i in range(n):
d[i]-=l #as long as d[i]<=0, Koa can stay at i
safeSpots=set()
ok=True
for i in range(n):
if d[i]+k<=0:
safeSpots.add(i)
if d[i]>0: #impossible no matter what
print('No')
ok=False
break
if ok==False:
continue
def getAdditionalDepth(t):
t2=t%(2*k)
if t2>k:
t2=2*k-t2
return t2
ok=True
t=k #starting on a safe spot. start moving as soon as the tide is low enough
if d[0]+getAdditionalDepth(t)>0:
t+=d[0]+getAdditionalDepth(t) #will be 0 at this time
d.append(-float('inf')) #d[n] is safe ground
for i in range(n):
if t>=2*k:t-=2*k #t is current time
if (i+1) in safeSpots:
t=k #set t to k (max depth)
continue
nextDepth=d[i+1]+getAdditionalDepth(t+1) #next depth if Koa moves over now
if nextDepth<=0:
t+=1
continue #ok to move to this index
else: #find the earliest time to move over, if possible
if t+1<=k:
ok=False #impossible because tide is increasing
break
earliestTime=t+nextDepth #after moving over now to i+1 (at t+1), must wait for nextDepth time before it's safe on i+1
t=earliestTime+1
if ok:
print('Yes')
else:
print('No')
```
Yes
| 91,106 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Submitted Solution:
```
def main():
t = int(input())
for i in range(t):
n, k, l = map(int, input().split())
d = tuple(map(int, input().split()))
output = "Yes" if _can_get_to_finish(d, k, l) else "No"
print(output)
def _can_get_to_finish(depths, max_tide_height, max_height_can_swim):
tide_heights_allowed = [max_height_can_swim - depth for depth in depths]
if any(allowed_height < 0 for allowed_height in tide_heights_allowed):
return False
get_tide_height = lambda time: _get_tide_height_by_time(time, max_tide_height)
next_pos = 0
last_checkpoint = None
while True:
prev_checkpoint = last_checkpoint
next_time = -tide_heights_allowed[next_pos]
while next_pos < len(tide_heights_allowed):
allowed_height = tide_heights_allowed[next_pos]
if allowed_height >= max_tide_height:
last_checkpoint = next_pos
next_pos += 1
break
if get_tide_height(next_time) > allowed_height:
how_much_must_wait = get_tide_height(next_time) - allowed_height
if next_time + how_much_must_wait > 0:
return False
next_time += how_much_must_wait
next_pos += 1
next_time += 1
if next_pos >= len(tide_heights_allowed):
return True
if last_checkpoint == prev_checkpoint:
return False
def _get_tide_height_by_time(time, max_tide_height):
time %= 2*max_tide_height
if time < max_tide_height:
result = time
else:
time_since_max = time - max_tide_height
result = max_tide_height - time_since_max
return result
if __name__ == '__main__':
main()
```
Yes
| 91,107 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Submitted Solution:
```
t = int(input())
while t>0:
n,k,l = map(int,input().split())
a = list(map(int,input().split()))
if max(a) > l:
print("No")
else:
for i in range(n):
if a[i] + k <= l:
a[i] = -1
ghata = -1
p = 1
y = 0
for i in range(n):
if a[i] == -1:
ghata = -1
else:
if ghata == -1:
ghata = l-a[i]
y = 0
if ghata == 0:
y = 1
ghata += 1
elif i != n-1 and a[i+1] != -1:
# y = 0
ghata = ghata-1
if l<ghata+a[i+1]:
ghata = l-a[i+1]
else:
if a[i]+ghata>l:
if y == 0:
if l<ghata+a[i]:
ghata = l-a[i]
if ghata == 0:
ghata += 1
y = 1
else:
ghata = ghata-1
else:
# print(i)
p = 0
break
else:
if y == 1 or ghata == 0:
ghata = ghata+1
y = 1
else:
ghata = ghata-1
# print(ghata,i)
if p == 0:
print("No")
else:
print("Yes")
t = t-1
```
Yes
| 91,108 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Submitted Solution:
```
for h in range(int(input())):
n, k, l = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))
dp = [0 for i in range(len(arr)+1)]
dp[0] = -1
# print(p)
there = True
for i in range(len(arr)):
if arr[i] > l:
there = False
break
elif arr[i]+k > l:
dp[i+1] = arr[i]
else:
dp[i+1] = -1
if there == False:
print("No")
continue
pointer = 0
for i in range(n+1):
if dp[i] == -1:
if i == n:
continue
elif i < n:
maxi = l-dp[i+1]
pointer = -maxi-1
else:
pointer += 1
if dp[i] + abs(pointer) > l:
if pointer >= 0:
there = False
break
else:
pointer = -(l-dp[i])
if there == False:
print("No")
else:
print("Yes")
```
Yes
| 91,109 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Submitted Solution:
```
T = int(input())
for _ in range(T):
n,k,l = map(int, input().split())
d = list(map(int, input().split()))
ranges = []
t = -102
co = 0
for i in range(n):
ch = [max(t+1, -l+d[i]), l-d[i]]
t = max(-l+d[i],t+1)
if k<=l-d[i]:
ch = [-102,102]
t = -101
ranges.append(ch)
if ranges[i][0]>ranges[i][1]:
print("NO")
co = 1
break
if co==0:
print("YES")
```
No
| 91,110 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Submitted Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
N, K, L = map(int, input().split())
A = list(map(int, input().split()))
A.append(-K)
if max(A) > L:
print("No")
exit()
ok = 1
k = -K-1
for a in A:
if k < 0:
k += 1
if a + k > L:
k = -(L - a)
else:
k += 1
if a + k > L:
ok = 0
break
elif a + K <= L:
k = -K+1
if ok:
print("Yes")
else:
print("No")
if __name__ == '__main__':
main()
```
No
| 91,111 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Submitted Solution:
```
from sys import stdin, stdout
# 5 2 3
# 1 2 3 2 2
#
def koa_and_beach(n, k, l, d_a):
sp_a = []
for i in range(len(d_a)):
if d_a[i] + k <= l:
sp_a.append(i)
if d_a[i] > l:
return 'No'
sp_a.append(n)
pre = -1
down = True
for i in sp_a:
ct = k
for j in range(pre + 1, i):
if down:
ct -= 1
else:
ct += 1
if d_a[j] + ct > l:
if down:
ct = d_a[j] + ct - l
else:
return 'No'
if ct == k:
down = True
elif ct == 0:
down = False
pre = i
return 'Yes'
# d + p[i] <= l
t = int(stdin.readline())
for _ in range(t):
n, k, l = map(int, stdin.readline().split())
d_a = list(map(int, stdin.readline().split()))
res = koa_and_beach(n, k, l, d_a)
stdout.write(str(res) + '\n')
```
No
| 91,112 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore.
She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n.
Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way:
* For a total of k seconds, each second, tide increases all depths by 1.
* Then, for a total of k seconds, each second, tide decreases all depths by 1.
* This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...).
Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore:
* In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1.
* As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always.
* Once Koa reaches the island at n+1 meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l.
The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
Example
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
Note
In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore.
In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ].
Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution:
* Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i].
* At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1.
* At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1.
* At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1.
* At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4.
* At t = 4 Koa is at x = 3 and she made it!
We can show that in test case 2 Koa can't get to the island.
Submitted Solution:
```
t = int(input())
while t>0:
n,k,l = map(int,input().split())
a = list(map(int,input().split()))
if max(a) > l:
print("No")
else:
for i in range(n):
if a[i] + k <= l:
a[i] = -1
ghata = -1
p = 1
for i in range(n):
if a[i] == -1:
ghata = -1
else:
if ghata == -1:
ghata = l-a[i]
if ghata == 0:
ghata += 1
elif i != n-1:
ghata = ghata-1
if l-a[i+1]<ghata:
ghata = l-a[i+1]
else:
if a[i]+((ghata-1)%k)+1>l:
p = 0
break
else:
ghata = ghata+1
if p == 0:
print("No")
else:
print("Yes")
t = t-1
```
No
| 91,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
import os,io
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def distance(graph,u,v):
visited = {i: True for i in graph}
stack = [(u,0)]
rp = 0
while stack:
node,p = stack.pop()
if node == v:
rp = p
break
if visited[node]:
visited[node]=False
for i in graph[node]:
if visited[i]:
stack.append((i,p+1))
return rp
def diameter(graph,root):
visited = {i:True for i in graph}
def inner(visited,root):
diam = 0
hl = []
if visited[root]:
visited[root] = False
for i in graph[root]:
if visited[i]:
h,diam1 = inner(visited,i)
hl.append(h)
diam = max(diam,diam1)
hl.extend([0,0])
h1,h2 = sorted(hl,reverse=True)[:2]
return max(h1,h2)+1,max(diam,h1+h2+1)
_,diam = inner(visited,root)
return diam
cases = int(input())
for t in range(cases):
n,a,b,da,db = list(map(int,input().split()))
if db <= 2*da:
for i in range(n-1):
_ = input()
print("Alice")
else:
graph = {i+1:[] for i in range(n)}
for i in range(n-1):
u,v = list(map(int,input().split()))
graph[u].append(v)
graph[v].append(u)
ab = distance(graph,a,b)
if ab <= da:
print("Alice")
else:
diam = diameter(graph,1)
if da >= diam//2:
print("Alice")
else:
print("Bob")
```
| 91,114 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
from sys import stdin
for _ in range(int(input())):
n,a,b,da,db=map(int,input().split())
a-=1
b-=1
go=[[] for _ in range(n)]
for _ in range(n-1):
x,y=map(int,stdin.readline().split())
x-=1
y-=1
go[x].append(y)
go[y].append(x)
MAX=0
re=[[] for _ in range(n)]
q=[(a,0,-1)]
go[a].append(-1)
while q!=[]:
node,level,pre=q[-1]
if node==b:
dis=level
if len(re[node])==len(go[node])-1:
re[node].extend([0,0])
re[node].sort()
MAX=max(MAX,re[node][-1]+re[node][-2])
re[pre].append(re[node][-1]+1)
q.pop()
continue
for x in go[node]:
if x!=pre:
q.append([x,level+1,node])
if dis<=da or da*2>=db or da*2>=MAX:
print('Alice')
else:
print('Bob')
```
| 91,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
# -*- coding: utf-8 -*-
# import bisect
# import heapq
# import math
# import random
# from collections import Counter, defaultdict, deque
# from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
# from fractions import Fraction
# from functools import lru_cache, reduce
# from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
# from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
error_print(e - s, 'sec')
return ret
return wrap
from collections import defaultdict
from functools import reduce
@mt
def slv(N, A, B, DA, DB, UV):
if 2*DA >= DB:
return 'Alice'
g = defaultdict(list)
for u, v in UV:
g[u].append(v)
g[v].append(u)
def dfs(u):
d = {u: 0}
s = [u]
while s:
u = s.pop()
for v in g[u]:
if v in d:
continue
d[v] = d[u] + 1
s.append(v)
return d
d = dfs(A)
if d[B] <= DA:
return 'Alice'
mv = reduce(lambda m, i: max(m, (d[i], i)), range(1, N+1), (-INF, -1))
# print(mv)
d = dfs(mv[1])
diam = max(d.values())
# print(diam)
if 2*DA >= diam:
return 'Alice'
return 'Bob'
def main():
for _ in range(read_int()):
N, A, B, DA, DB = read_int_n()
UV = [read_int_n() for _ in range(N-1)]
print(slv(N, A, B, DA, DB, UV))
if __name__ == '__main__':
main()
```
| 91,116 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
def dfs(i):
q=[i]
pa=[-1 for i in range(n)]
de=[0 for i in range(n)]
while q:
x=q.pop()
for y in tr[x]:
if y==pa[x]:continue
pa[y]=x
de[y]=de[x]+1
q.append(y)
return(de)
for _ in range(int(input())):
n,a,b,da,db=map(int,input().split())
a-=1;b-=1
tr=[[] for i in range(n)]
for i in range(n-1):
u,v=map(int,input().split())
u-=1;v-=1
tr[u].append(v)
tr[v].append(u)
bbb=dfs(a);dist=bbb[b]
ci=bbb.index(max(bbb))
dimr=max(dfs(ci))
if dist<=da:
print("Alice")
elif 2*da>=dimr:
print("Alice")
elif db<=2*da:
print("Alice")
else:
print("Bob")
```
| 91,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
n, a, b, da, db = map(int,input().split())
C = [list(map(int,input().split())) for j in range(n-1)]
for j in range(n-1):
for k in range(2):
C[j][k] -= 1
a -= 1
b -= 1
M = [[] for j in range(n)]
for j in range(n-1):
M[C[j][0]].append(C[j][1])
M[C[j][1]].append(C[j][0])
V = [-1] * n
V[a] = 0
Q = [[a, 0]]
s = 0
while len(Q) > s:
V[Q[s][0]] = Q[s][1]
for x in M[Q[s][0]]:
if V[x] == -1:
Q.append([x, Q[s][1]+1])
s += 1
mi = V.index(max(V))
# print(V,a,b)
if V[b] <= da:
print("Alice")
continue
V = [-1] * n
V[mi] = 0
Q = [[mi, 0]]
s = 0
while len(Q) > s:
V[Q[s][0]] = Q[s][1]
for x in M[Q[s][0]]:
if V[x] == -1:
Q.append([x, Q[s][1]+1])
s += 1
mi = V.index(max(V))
# print(V)
if db >= da*2 + 1 and max(V) >= da*2 + 1:
print("Bob")
else:
print("Alice")
```
| 91,118 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
from sys import stdin
def inp():
return stdin.buffer.readline().rstrip().decode('utf8')
def itg():
return int(stdin.buffer.readline())
def mpint():
return map(int, stdin.buffer.readline().split())
# ############################## import
from copy import deepcopy
def to_tree(graph, root=0):
"""
graph: undirected graph (adjacency list)
:return directed graph that parent -> children
"""
graph[:] = map(set, graph)
stack = [[root]]
while stack:
if not stack[-1]:
del stack[-1]
continue
vertex = stack[-1].pop()
for e in graph[vertex]:
graph[e].remove(vertex)
stack.append(list(graph[vertex]))
graph[:] = map(list, graph)
def to_graph(tree, root=0):
"""
:return undirected graph (adjacency list)
"""
tree[:] = map(set, tree)
for node1, node_set in enumerate(deepcopy(tree)):
for node2 in node_set:
tree[node2].add(node1)
tree[:] = map(list, tree)
def tree_distance(tree, u, v):
# bfs
if u == v:
return 0
graph = deepcopy(tree)
to_graph(graph)
graph[:] = map(set, graph)
curr = {u}
step = 1
while True:
nxt = set()
for node in curr:
if v in graph[node]:
return step
nxt |= graph[node]
curr = nxt
step += 1
def tree_bfs(tree, start=0, flat=False):
stack = [start]
result = []
while stack:
new_stack = []
if flat:
result.extend(stack)
else:
result.append(stack)
for node in stack:
new_stack.extend(tree[node])
stack = new_stack
return result
def tree_farthest(tree):
"""
:returns u, v, n
that u, v is the both ends of one of the longest chain
and the longest chain has n nodes
"""
# 2 times bfs
node1 = tree_bfs(tree, flat=True)[-1]
to_graph(tree)
to_tree(tree, node1)
bfs_data = tree_bfs(tree, node1)
node2 = bfs_data[-1][-1]
return node1, node2, len(bfs_data)
# ############################## main
def solve():
n, a, b, da, db = mpint()
a -= 1
b -= 1
tree = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = mpint()
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
if db - da < 2:
return True
to_tree(tree)
if tree_distance(tree, a, b) <= da:
return True
longest = tree_farthest(tree)[2]
dis = longest >> 1
return dis <= da or db < da * 2 + 1
for __ in range(itg()):
print("Alice" if solve() else "Bob")
# Please check!
```
| 91,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
from sys import stdin
def input():
return stdin.readline().strip()
tests = int(input())
for t in range(tests):
n, a, b, da, db = list(map(int, input().split()))
edge_ls = [[] for _ in range(n+1)]
for _ in range(n-1):
e1, e2 = list(map(int, input().split()))
edge_ls[e1].append(e2)
edge_ls[e2].append(e1)
if da*2<db:
stack = [[a,0]]
visited = [False for _ in range(n+1)]
visited[a] = True
found = None
furthest_edge = None
furthest_dist = -1
# find distance between a and b start points
while stack:
curr, curr_step = stack.pop(-1)
if curr_step > furthest_dist:
furthest_dist = curr_step
furthest_edge = curr
for item in edge_ls[curr]:
if not visited[item]:
stack.append([item, curr_step+1])
visited[item] = True
if item == b:
found = curr_step+1
# find longest sinmple path length
stack = [[furthest_edge,1]]
visited = [False for _ in range(n+1)]
visited[furthest_edge] = True
furthest_dist = -1
while stack:
curr, curr_step = stack.pop(-1)
if curr_step > furthest_dist:
furthest_dist = curr_step
for item in edge_ls[curr]:
if not visited[item]:
stack.append([item, curr_step+1])
visited[item] = True
if found > da and furthest_dist >= (da*2)+2:
print('Bob')
else:
print('Alice')
else:
print('Alice')
```
| 91,120 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
# if da > db then Alice wins
# if dist(a, b) <= da then Alice wins
# if da+da >= db then Alice wins because Bob can't jump over Alice
# and go to some other branch of tree
# otherwise is there always an element at more than 2*da away?
# Optimizations if sync_with_stdio False
# from https://github.com/Cheran-Senthil/PyRival
import atexit
from io import StringIO
import sys
input = iter(sys.stdin.read().splitlines()).__next__
sys.stdout = StringIO()
atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
def furthest(graph, source):
S = [(source, 0)]
furthest_node = source
furthest_dist = 0
discovered = [False]*len(graph)
while S:
u, dist = S.pop()
if dist > furthest_dist:
furthest_node = u
furthest_dist = dist
if discovered[u]:
continue
discovered[u] = True
for v in graph[u]:
S.append((v, dist+1))
return furthest_node, furthest_dist
def distance(graph, source, dest):
S = [(source, 0)]
discovered = set()
while S:
u, dist = S.pop()
if u == dest:
return dist
if u in discovered:
continue
discovered.add(u)
for v in graph[u]:
S.append((v, dist+1))
t = int(input())
for _ in range(t):
n, a, b, da, db = map(int, input().split())
if da+da >= db:
for edge in range(n-1):
input()
print('Alice')
continue
graph = [[] for node in range(n)]
for edge in range(n-1):
u, v = [int(i)-1 for i in input().split()]
graph[u].append(v)
graph[v].append(u)
if distance(graph, a-1, b-1) <= da:
print('Alice')
continue
diameter = furthest(graph, furthest(graph, 0)[0])[1]
if da+da >= diameter:
print('Alice')
else:
print('Bob')
```
| 91,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for rrr in range(t):
n,a,b,da,db = list(map(int,input().split()))
a -= 1
b -= 1
if da>=db:
for _ in range(n-1):
x,y = list(map(int,input().split()))
print('Alice')
else:
N = [[] for _ in range(n)]
V = [0 for _ in range(n)]
D = [0 for _ in range(n)]
for _ in range(n-1):
x,y = list(map(int,input().split()))
x -= 1
y -= 1
N[x].append(y)
N[y].append(x)
Q = [a]
V[a] = 1
depth = 0
done = 0
while Q:
depth += 1
new_Q = []
for node in Q:
for child in N[node]:
if V[child]==0:
new_Q.append(child)
V[child]=1
if child==b:
if depth<=da:
print('Alice')
done = 1
Q = new_Q
if done==0:
V = [0 for _ in range(n)]
Q = [0]
OR = [0]
V[0] = 1
depth = 0
while Q:
new_Q = []
for node in Q:
for child in N[node]:
if V[child]==0:
new_Q.append(child)
V[child]=1
OR.append(child)
Q = new_Q
depth += 1
Q = [OR[-1]]
V = [0 for _ in range(n)]
V[OR[-1]] = 1
depth = 0
while Q:
new_Q = []
for node in Q:
for child in N[node]:
if V[child]==0:
new_Q.append(child)
V[child]=1
OR.append(child)
Q = new_Q
depth += 1
depth -= 1
if depth > 2*da and db>2*da:
print('Bob')
else:
print('Alice')
```
Yes
| 91,122 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
gans = []
for _ in range(int(input())):
n, a, b, da, db = map(int, input().split())
a -= 1
b -= 1
u = []
for i in range(n):
u.append([])
for i in range(n - 1):
v1, v2 = map(lambda x: int(x) - 1, input().split())
u[v1].append(v2)
u[v2].append(v1)
ind = a
q = [ind]
q0 = 0
INF = 100000000
d = [INF] * n
d[ind] = 0
while len(q) > q0:
v = q[q0]
q0 += 1
for i in u[v]:
if d[i] > d[v] + 1:
d[i] = d[v] + 1
q.append(i)
if d[b] <= da:
gans.append('Alice')
continue
ind = -1
mx = max(d)
for i in range(n):
if d[i] == mx:
ind = i
break
q = [ind]
q0 = 0
d = [INF] * n
d[ind] = 0
while len(q) > q0:
v = q[q0]
q0 += 1
for i in u[v]:
if d[i] > d[v] + 1:
d[i] = d[v] + 1
q.append(i)
D = max(d)
#print(*d)
if db > 2 * da and 2 * da < D:
gans.append('Bob')
else:
gans.append('Alice')
print('\n'.join(gans))
```
Yes
| 91,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
from sys import stdin, stdout
get_string = lambda: stdin.readline().strip('\n')
get_intmap = lambda: map( int, get_string().split(' ') )
def testcase():
n, a, b, da, db = get_intmap()
adj = [[] for i in range(n+1)]
for i in range(n-1):
u, v = get_intmap()
adj[u].append(v)
adj[v].append(u)
used = [ 0 ] * (n + 1)
frontier, nxt, used[a], distance = [ a ], [], 1, 0
while len(frontier):
distance += 1
for u in frontier:
for v in adj[u]:
if used[v]: continue
if v == b: distance_ab = distance
used[v] = 1
nxt.append(v)
if nxt == []: #bfs is about to end
leaf_node = frontier.pop()
frontier, nxt = nxt, []
if distance_ab <= da: print("Alice"); return
used = [ 0 ] * (n + 1)
frontier, nxt, used[leaf_node], distance = [ leaf_node ], [], 1, 0
while len(frontier):
distance += 1
for u in frontier:
for v in adj[u]:
if used[v]: continue
used[v] = 1
nxt.append(v)
if nxt == []: #bfs is about to end
tree_diameter = distance - 1
frontier, nxt = nxt, []
#print(a, leaf_node, tree_diameter,da,db)
if tree_diameter <= 2 * da: print("Alice"); return
if db <= 2 * da: print("Alice")
else: print("Bob")
#testcase();quit()
for t in range(int(input())):
testcase()
```
Yes
| 91,124 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
def dfs(x,p):
l = 0
for i in graph[x]:
if i!=p:
depth[i]=depth[x]+1
cur = 1+dfs(i,x)
diam[0] = max(diam[0],cur+l)
l = max(l,cur)
return l
for _ in range (int(input())):
n,a,b,da,db = [int(i) for i in input().split()]
graph = [[] for i in range (n)]
for i in range (n-1):
uu,vv = [int(i)-1 for i in input().split()]
graph[uu].append(vv)
graph[vv].append(uu)
depth=[0]*n
diam = [0]
temp = dfs(a-1,-1)
if 2*da >= min(diam[0],db) or depth[b-1]<=da:
print('Alice')
else:
print('Bob')
```
Yes
| 91,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
tests = int(input())
for t in range(tests):
n, a, b, da, db = list(map(int, input().split()))
edge_ls = [[] for _ in range(n+1)]
for _ in range(n-1):
e1, e2 = list(map(int, input().split()))
edge_ls[e1].append(e2)
edge_ls[e2].append(e1)
if da*2<db:
stack = [[a,0]]
visited = [False for _ in range(n+1)]
visited[a] = True
found = None
while stack and found is None:
curr, curr_step = stack.pop(-1)
for item in edge_ls[curr]:
if not visited[item]:
stack.append([item, curr_step+1])
visited[item] = True
if item == b:
found = curr_step+1
break
if found > da:
print('Bob')
else:
print('Alice')
else:
print('Alice')
```
No
| 91,126 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
import sys
ii = lambda: sys.stdin.readline().strip()
idata = lambda: [int(x) for x in ii().split()]
def dfs_2(graph, ver):
visited = set()
visited.add(ver)
depth = [0] * (len(graph) + 1)
queue = [ver]
while queue:
vertex = queue.pop(0)
for i in graph[vertex]:
if i not in visited:
visited.add(i)
depth[i] = depth[vertex] + 1
queue += [i]
return depth
def solve():
n, a, b, da, db = idata()
graph = {}
for i in range(n - 1):
v, u = idata()
if not v in graph:
graph[v] = [u]
else:
graph[v] += [u]
if not u in graph:
graph[u] = [v]
else:
graph[u] += [v]
global t
if t != 105 and t > 3:
return
print(n, a, b, da, db)
q = dfs_2(graph, a)
if q[b] <= da:
print('Alice')
return
q.sort()
y = q[-1]
for i in range(len(q) - 1, 0, -1):
if q[i] == q[i - 1]:
y += q[i]
break
if y <= 2 * da:
print('Alice')
return
if db <= 2 * da:
print('Alice')
return
print('Bob')
return
for t in range(int(ii())):
solve()
```
No
| 91,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
import sys
from collections import deque
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
n, a, b, da, db = map(int, input().split())
e = [[] for _ in range(n+1)]
for _ in range(n-1):
u, v = map(int, input().split())
e[u].append(v)
e[v].append(u)
par = [0]*(n+1)
q, dis, leaf = deque([a]), [0]*(n+1), []
while q:
u = q.popleft()
is_leaf = 1
for v in e[u]:
if v == par[u]: continue
q.append(v)
par[v], dis[v] = u, dis[u]+1
is_leaf = 0
if is_leaf: leaf.append(dis[u])
leaf.sort(reverse=True)
dis_ab = dis[b]
dis_mx = 0
if len(leaf) == 1: dis_mx = leaf[0]
elif len(leaf) > 1: dis_mx = leaf[0] + leaf[1]
if dis_ab <= da or min(dis_mx, db) <= 2*da:
print('Alice')
else:
print('Bob')
```
No
| 91,128 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
import sys
ii = lambda: sys.stdin.readline().strip()
idata = lambda: [int(x) for x in ii().split()]
def dfs_2(graph, ver):
visited = set()
depth = [0] * (len(graph) + 1)
queue = [ver]
while queue:
vertex = queue.pop(0)
for i in graph[vertex]:
if i not in visited:
visited.add(i)
depth[i] = depth[vertex] + 1
queue += [i]
return depth
def solve():
n, a, b, da, db = idata()
graph = {}
for i in range(n - 1):
v, u = idata()
if not v in graph:
graph[v] = [u]
else:
graph[v] += [u]
if not u in graph:
graph[u] = [v]
else:
graph[u] += [v]
q = dfs_2(graph, a)
if q[b] <= da:
print('Alice')
return
q.sort()
y = q[-1]
for i in range(len(q) - 1, 0, -1):
if q[i] == q[i - 1]:
y += q[i]
break
if y <= 2 * da:
print('Alice')
return
if db <= 2 * da:
print('Alice')
return
print('Bob')
return
for t in range(int(ii())):
solve()
```
No
| 91,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Tags: combinatorics, dp, strings
Correct Solution:
```
from collections import defaultdict as dd
mod = 10**9 + 7
pw = {-1:0, 0:1}
for i in range(1,200001):
pw[i] = pw[i-1]*3 % mod
def solve(st, n):
a,c,q = dd(int), dd(int), dd(int)
for i,it in enumerate(st):
a[i], c[i], q[i] = a[i-1], c[i-1], q[i-1]
if it == 'a':
a[i]+=1
elif it == 'c':
c[i]+=1
elif it == '?':
q[i]+=1
ans = 0
for i in range(n):
if st[i] in '?b':
ca, q1 = a[i-1], q[i-1]
cc, q2 = c[n-1] - c[i], q[n-1] - q[i]
ta = ( ca*pw[q1]% mod + q1*pw[q1-1]% mod ) % mod
tc = ( cc*pw[q2]% mod + q2*pw[q2-1]% mod ) % mod
ans += ta * tc
ans %= mod
return ans
n = int(input())
st = input()
ans = solve(st, n)
print(ans)
```
| 91,130 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Tags: combinatorics, dp, strings
Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time
# sys.setrecursionlimit(5*10**5)
inf = 10**20
mod = 10**9 + 7
def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return list(input().split())
def S(): return input()
n = II()
s = S()
pow_calc = [1 for _ in range(n+1)]
for i in range(1,n+1):
pow_calc[i] = pow_calc[i-1] * 3
pow_calc[i] %= mod
def solve():
la = lq = rc = rq = 0
ans = 0
for char in s:
if char == 'c': rc += 1
if char == '?': rq += 1
for char in s:
if char == 'c': rc -= 1
if char == '?': rq -= 1
if char in {'?', 'b'}:
l = (la * pow_calc[lq]) % mod + (lq * pow_calc[lq-1]) % mod
l %= mod
r = (rc * pow_calc[rq]) % mod + (rq * pow_calc[rq-1]) % mod
r %= mod
ans += (l * r) % mod
ans %= mod
if char == 'a':
la += 1
if char == '?':
lq += 1
return ans
def main():
ans = solve()
print(ans)
return 0
main()
```
| 91,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Tags: combinatorics, dp, strings
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
s = input()[:-1]
dp = [[0]*4 for _ in range(n+1)]
dp[0][0] = 1
MOD = 10**9+7
for i in range(n):
if s[i]!='?':
dp[i+1][0] = dp[i][0]
dp[i+1][1] = (dp[i][1]+(dp[i][0] if s[i]=='a' else 0))%MOD
dp[i+1][2] = (dp[i][2]+(dp[i][1] if s[i]=='b' else 0))%MOD
dp[i+1][3] = (dp[i][3]+(dp[i][2] if s[i]=='c' else 0))%MOD
else:
dp[i+1][0] = 3*dp[i][0]%MOD
dp[i+1][1] = (dp[i][0]+3*dp[i][1])%MOD
dp[i+1][2] = (dp[i][1]+3*dp[i][2])%MOD
dp[i+1][3] = (dp[i][2]+3*dp[i][3])%MOD
print(dp[n][3])
```
| 91,132 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Tags: combinatorics, dp, strings
Correct Solution:
```
n = int(input())
word = input()
P = [[0, 0, 0] for _ in range(n + 1)]
P_w = [0, 0, 0]
cnt = 1
mod = int(1e9 + 7)
for i in range(n):
P[i+1][0] = P[i][0]
P[i+1][1] = P[i][1]
P[i+1][2] = P[i][2]
if word[i] == "a":
P[i+1][0] = (P[i][0] + cnt) % mod
elif word[i] == "b":
P[i+1][1] = (P[i][1] + P[i][0]) % mod
elif word[i] == "c":
P[i+1][2] = (P[i][2] + P[i][1]) % mod
elif word[i] == "?":
P[i+1][2] = (3 * P[i][2] + P[i][1]) % mod
P[i+1][1] = (3 * P[i][1] + P[i][0]) % mod
P[i+1][0] = (3 * P[i][0] + cnt) % mod
cnt = (cnt * 3) % mod
print(P[-1][2])
```
| 91,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Tags: combinatorics, dp, strings
Correct Solution:
```
Mod = 10 ** 9 + 7
n = int(input())
s = input()
cnt, a, ab, abc = 1, 0, 0, 0
for i in range(len(s)):
if s[i] == 'a':
a += cnt
a %= Mod
elif s[i] == 'b':
ab += a
ab %= Mod
elif s[i] == 'c':
abc += ab
abc %= Mod
else:
abc *= 3
abc += ab
abc %= Mod
ab *= 3
ab += a
ab %= Mod
a *= 3
a += cnt
a %= Mod
cnt *= 3
cnt %= Mod
print(abc)
```
| 91,134 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Tags: combinatorics, dp, strings
Correct Solution:
```
from bisect import bisect_left, bisect_right
class Result:
def __init__(self, index, value):
self.index = index
self.value = value
class BinarySearch:
def __init__(self):
pass
@staticmethod
def greater_than(num: int, func, size: int = 1):
"""Searches for smallest element greater than num!"""
if isinstance(func, list):
index = bisect_right(func, num)
if index == len(func):
return Result(None, None)
else:
return Result(index, func[index])
else:
alpha, omega = 0, size - 1
if func(omega) <= num:
return Result(None, None)
while alpha < omega:
if func(alpha) > num:
return Result(alpha, func(alpha))
if omega == alpha + 1:
return Result(omega, func(omega))
mid = (alpha + omega) // 2
if func(mid) > num:
omega = mid
else:
alpha = mid
@staticmethod
def less_than(num: int, func, size: int = 1):
"""Searches for largest element less than num!"""
if isinstance(func, list):
index = bisect_left(func, num) - 1
if index == -1:
return Result(None, None)
else:
return Result(index, func[index])
else:
alpha, omega = 0, size - 1
if func(alpha) >= num:
return Result(None, None)
while alpha < omega:
if func(omega) < num:
return Result(omega, func(omega))
if omega == alpha + 1:
return Result(alpha, func(alpha))
mid = (alpha + omega) // 2
if func(mid) < num:
alpha = mid
else:
omega = mid
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def pre(s):
n = len(s)
pi = [0] * n
for i in range(1, n):
j = pi[i - 1]
while j and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
def prod(a):
ans = 1
for each in a:
ans = (ans * each)
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
bs = BinarySearch()
for _ in range(int(input()) if not True else 1):
n = int(input())
s = input()
mod = 10**9 + 7
a = []
b = []
c = []
q = []
ans = 0
for i in range(n):
if s[i] == 'a': a+=[i]
elif s[i] == 'b': b += [i]
elif s[i] == 'c': c += [i]
else: q += [i]
q0 = pow(3, len(q), mod)
q1 = pow(3, len(q)-1, mod) if len(q)>0 else 0
q2 = pow(3, len(q)-2, mod) if len(q)>1 else 0
q3 = pow(3, len(q)-3, mod) if len(q)>2 else 0
# ab*
# abc
bc, bq = [], []
for i in b:
ind, ind2 = bs.greater_than(i, c).index, bs.greater_than(i, q).index
count = 0 if ind is None else len(c)-ind
count2 = 0 if ind2 is None else len(q)-ind2
bc += [count]
bq += [count2]
for i in range(len(bc)-2, -1, -1):
bc[i] += bc[i+1]
bq[i] += bq[i+1]
for i in a:
ind = bs.greater_than(i, b).index
if ind is None:continue
if bc[ind]:
ans += bc[ind] * q0
ans = ans % mod
if bq[ind]:
ans += bq[ind] * q1
ans = ans % mod
# *bc
# *b*
for i in q:
ind = bs.greater_than(i, b).index
if ind is None:continue
if bc[ind]:
ans += bc[ind] * q1
ans = ans % mod
if bq[ind]:
ans += bq[ind] * q2
ans = ans % mod
#a*c
#a**
bc, bq = [], []
for i in q:
ind, ind2 = bs.greater_than(i, c).index, bs.greater_than(i, q).index
count = 0 if ind is None else len(c) - ind
count2 = 0 if ind2 is None else len(q) - ind2
bc += [count]
bq += [count2]
for i in range(len(bc) - 2, -1, -1):
bc[i] += bc[i + 1]
bq[i] += bq[i + 1]
for i in a:
ind = bs.greater_than(i, q).index
if ind is None:continue
if bc[ind]:
ans += bc[ind] * q1
ans = ans % mod
if bq[ind]:
ans += bq[ind] * q2
ans = ans % mod
# **c
# ***
for i in q:
ind = bs.greater_than(i, q).index
if ind is None: continue
if bc[ind]:
ans += bc[ind] * q2
ans = ans % mod
if bq[ind]:
ans += bq[ind] * q3
ans = ans % mod
print(ans)
```
| 91,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Tags: combinatorics, dp, strings
Correct Solution:
```
mod=10**9+7
n=int(input())
s=input()
na=0
nb=0
nc=0
rt=1
for i in range(n):
if s[i]=='?':
nc=3*nc+nb
nb=3*nb+na
na=3*na+rt
rt*=3
else:
if s[i]=='a':
na+=rt
elif s[i]=='b':
nb+=na
else:
nc+=nb
nc%=mod
na%=mod
nb%=mod
rt%=mod
print(nc%mod)
```
| 91,136 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Tags: combinatorics, dp, strings
Correct Solution:
```
mod=10**9+7
n=int(input())
s=input()[::-1]
#dp=[c,bc,abc]
dp=[[0]*3 for _ in range(n+1)]
pows=[1]
for i in range(n):
pows.append((pows[-1]*3)%mod)
cnt=0
for i in range(n):
if s[i]=='a':
dp[i+1][0]+=dp[i][0]
dp[i+1][1]+=dp[i][1]
dp[i+1][2]+=dp[i][2]+dp[i][1]
elif s[i]=='b':
dp[i+1][0]+=dp[i][0]
dp[i+1][1]+=dp[i][1]+dp[i][0]
dp[i+1][2]+=dp[i][2]
elif s[i]=='c':
dp[i+1][0]+=dp[i][0]+pows[cnt]
dp[i+1][1]+=dp[i][1]
dp[i+1][2]+=dp[i][2]
elif s[i]=='?':
#a
dp[i+1][0]+=dp[i][0]
dp[i+1][1]+=dp[i][1]
dp[i+1][2]+=dp[i][2]+dp[i][1]
#b
dp[i+1][0]+=dp[i][0]
dp[i+1][1]+=dp[i][1]+dp[i][0]
dp[i+1][2]+=dp[i][2]
#c
dp[i+1][0]+=dp[i][0]+pows[cnt]
dp[i+1][1]+=dp[i][1]
dp[i+1][2]+=dp[i][2]
cnt+=1
dp[i+1][0]%=mod
dp[i+1][1]%=mod
dp[i+1][2]%=mod
print(dp[n][2])
```
| 91,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Submitted Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.readline
N = int(input())
S = input().rstrip('\n')
a_num = [0] * (N+1)
q_num_left = [0] * (N+1)
for i, s in enumerate(S):
a_num[i+1] = a_num[i]
q_num_left[i+1] = q_num_left[i]
if s == "a":
a_num[i+1] += 1
if s == "?":
q_num_left[i+1] += 1
S_rev = S[::-1]
c_num = [0] * (N+1)
q_num_right = [0] * (N+1)
for i, s in enumerate(S_rev):
c_num[i+1] = c_num[i]
q_num_right[i+1] = q_num_right[i]
if s == "c":
c_num[i+1] += 1
if s == "?":
q_num_right[i+1] += 1
ans = 0
k = q_num_left[-1]
k0 = pow(3, k, mod)
k1 = pow(3, max(0, k-1), mod)
k2 = pow(3, max(0, k-2), mod)
k3 = pow(3, max(0, k-3), mod)
for i, s in enumerate(S):
if s == "b":
# ac
ans = (ans + ((a_num[i] * c_num[N - i - 1])%mod * k0)%mod)%mod
# ?c
ans = (ans + ((q_num_left[i] * c_num[N - i - 1])%mod * k1)%mod)%mod
# a?
ans = (ans + ((a_num[i] * q_num_right[N - i - 1])%mod * k1)%mod)%mod
# ??
ans = (ans + ((q_num_left[i] * q_num_right[N - i - 1]) % mod * k2) % mod) % mod
elif s == "?":
# ac
ans = (ans + ((a_num[i] * c_num[N - i - 1]) % mod * k1) % mod) % mod
# ?c
ans = (ans + ((q_num_left[i] * c_num[N - i - 1]) % mod * k2) % mod) % mod
# a?
ans = (ans + ((a_num[i] * q_num_right[N - i - 1]) % mod * k2) % mod) % mod
# ??
ans = (ans + ((q_num_left[i] * q_num_right[N - i - 1]) % mod * k3) % mod) % mod
print(ans)
if __name__ == '__main__':
main()
```
Yes
| 91,138 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Submitted Solution:
```
n=int(input())
s=input()
a=0
b=0
c=0
v=1
mod = 10 ** 9 + 7
for i in range(n):
if s[i] == 'a':
a += v
elif s[i]=='b':
b += a
elif s[i]=='c':
c += b
else:
c=(3 * c + b) % mod
b=(3 * b + a) % mod
a=(3 * a + v) % mod
v=(3 * v) % mod
print(c % mod)
```
Yes
| 91,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Submitted Solution:
```
n=int(input())
s=input()
dp=[[0,0,0]for i in range(n)]
ct=1
mod=10**9+7
for i in range(n):
if i==0:
if s[i]=='?':ct*=3
if s[i]=='a' or s[i]=='?':dp[i][0]+=1
else:
aa,bb,cc=dp[i-1]
if s[i]=='a':
dp[i][0]=aa+ct
dp[i][1]=bb
dp[i][2]=cc
if s[i]=='b':
dp[i][0]=aa
dp[i][1]=aa+bb
dp[i][2]=cc
if s[i]=='c':
dp[i][0]=aa
dp[i][1]=bb
dp[i][2]=bb+cc
if s[i]=='?':
dp[i][0]=aa*3+ct
dp[i][1]=bb*3+aa
dp[i][2]=cc*3+bb
ct*=3
ct%=mod
dp[i][0]%=mod
dp[i][1]%=mod
dp[i][2]%=mod
print(dp[-1][-1])
```
Yes
| 91,140 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Submitted Solution:
```
import math
import sys
from sys import stdin, stdout
ipi = lambda: int(stdin.readline())
ipil = lambda: map(int, stdin.readline().split())
ipf = lambda: float(stdin.readline())
ipfl = lambda: map(float, stdin.readline().split())
ips = lambda: stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + "\n")
outl = lambda x: print(*x)
n = ipi()
s = ips()
a_cnt = 0
ab_cnt = 0
qst_cnt = 0
ans = 0
mod = int(1e9 + 7)
for i in range(n):
if s[i] == 'a':
a_cnt += pow(3, qst_cnt, mod)
elif s[i] == 'b':
ab_cnt += a_cnt
elif s[i] == 'c':
ans += ab_cnt
else:
ans *= 3
ans += ab_cnt
ab_cnt *= 3
ab_cnt += a_cnt
a_cnt *= 3
a_cnt += pow(3, qst_cnt, mod)
qst_cnt += 1
a_cnt %= mod
ab_cnt %= mod
ans %= mod
print(ans)
```
Yes
| 91,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Submitted Solution:
```
class CombsABC:
def __init__(self):
self.ft = 0
def find_subs(self, strs):
t = 0
for a in range(len(strs)):
if strs[a] == 'a':
for b in range(a + 1, len(strs)):
if strs[b] == 'b':
for c in range(b + 1, len(strs)):
if strs[c] == 'c':
t += 1
self.ft += t
def find_str(self, s, pos, i):
if i > len(pos) - 1:
return s
a = self.find_str(s[:pos[i]] + 'a' + s[pos[i] + 1:], pos, i + 1)
if a: self.find_subs(a)
b = self.find_str(s[:pos[i]] + 'b' + s[pos[i] + 1:], pos, i + 1)
if b: self.find_subs(b)
c = self.find_str(s[:pos[i]] + 'c' + s[pos[i] + 1:], pos, i + 1)
if c: self.find_subs(c)
l = int(input())
s = input() # 'ac?b?c'
pos = [_ for _ in range(len(s)) if s[_] == '?']
ins = CombsABC()
ins.find_str(s, pos, 0)
print(ins.ft)
```
No
| 91,142 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Submitted Solution:
```
n = int(input())
S = input()
a = 0
b = 0
tot = 0
q = 0
for s in S:
if s == 'a':
a += 1
elif s == 'b':
b += a
elif s == 'c':
tot += b
else:
tot = tot*3 + b
b = b*3 + a
a = a*3 + 3**q
q += 1
print(tot%(10**9 + 7))
```
No
| 91,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Submitted Solution:
```
n=int(input())
s=list(input())
A,B,C=[0]*n,[0]*n,[0]*n
if s[n-1]=="c" or s[n-1]=="?":
C[-1]=1
for i in range(n-2,-1,-1):
if s[i]=="c":
C[i]=C[i+1]+1
A[i]=A[i+1]
B[i]=B[i+1]
elif s[i]=="b":
B[i]=B[i+1]+C[i+1]
C[i]=C[i+1]
A[i]=A[i+1]
elif s[i]=="a":
A[i]=A[i+1]+B[i+1]
B[i]=B[i+1]
C[i]=C[i+1]
else:
A[i]=3*A[i+1]+B[i+1]
B[i]=3*B[i+1]+C[i+1]
C[i]=3*C[i+1]+1
print(A[0])
```
No
| 91,144 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"].
Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7.
A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6).
Input
The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s.
The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
Output
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7.
Examples
Input
6
ac?b?c
Output
24
Input
7
???????
Output
2835
Input
9
cccbbbaaa
Output
0
Input
5
a???c
Output
46
Note
In the first example, we can obtain 9 strings:
* "acabac" — there are 2 subsequences "abc",
* "acabbc" — there are 4 subsequences "abc",
* "acabcc" — there are 4 subsequences "abc",
* "acbbac" — there are 2 subsequences "abc",
* "acbbbc" — there are 3 subsequences "abc",
* "acbbcc" — there are 4 subsequences "abc",
* "accbac" — there is 1 subsequence "abc",
* "accbbc" — there are 2 subsequences "abc",
* "accbcc" — there are 2 subsequences "abc".
So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
Submitted Solution:
```
import sys
input = sys.stdin.readline
# import collections
n = int(input())
# a = list(map(int, input().split()))
s = input()
a = [0] * n
aq = [0] * n
c = [0] * n
cq = [0] * n
c1 = 0
c1q = 0
for i in range(1, len(s)):
if s[i] == "c":
c1 += 1
if s[i] == "?":
c1q += 1
c[0] = c1
cq[0] = c1q
for i in range(1, n-1):
if s[i-1] == "a":
a[i] = (a[i-1] + 1)
else:
a[i] = (a[i-1])
if s[i-1] == "?":
aq[i] = (aq[i-1] + 1)
else:
aq[i] = (aq[i-1])
if s[i] == "c":
c[i] = (c[i-1] - 1)
else:
c[i] = (c[i-1])
if s[i] == "?":
cq[i] = (cq[i-1] - 1)
else:
cq[i] = (cq[i-1])
#print(a, aq, c, cq)
sm = 0
for i in range(n):
if s[i] == "b" or s[i] == "?":
sm += (a[i] * 3**aq[i] + aq[i] * 3**(aq[i]-1)) * (c[i] * 3**cq[i] + cq[i] * 3**(cq[i]-1))
print(int(sm))
```
No
| 91,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
# return dijkstraSegTree(*args)
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
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))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
```
| 91,146 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
return dijkstraSegTree(*args)
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
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))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
```
| 91,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
return dijkstraHeapComparator(*args)
# return dijkstraSegTree(*args)
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
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))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
```
| 91,148 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
# return dijkstraSegTree(*args)
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
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))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
```
| 91,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args) # 2979 ms
return dijkstraHeapComparatorWrong(*args) # 2823 ms
# return dijkstraHeapComparator(*args) # 2370 ms
# return dijkstraSegTree(*args) # 2417 ms with inf=float('inf), 2995 ms with inf=-1
# return dijkstraSortedList(*args) # 2995 ms
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
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))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
```
| 91,150 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
return dijkstraSegTree(*args) # with inf = -1
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if True:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
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))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
```
| 91,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
# return dijkstraSegTree(*args)
return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
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))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
```
| 91,152 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Submitted Solution:
```
from collections import defaultdict
import heapq
def calculate_distances(graph, starting_vertex, n):
ans = [float('inf') for i in range(n+1)]
ans[1] = 0
pq = [((0, float('inf'), float('-inf')), starting_vertex)]
while len(pq) > 0:
cur_lst, current_vertex = heapq.heappop(pq)
cur_dist, cur_min, cur_max = cur_lst
# if cur_dist > ans[current_vertex][0]:
# continue
if cur_max == float('-inf'):
cur_weight_sum = cur_dist
else:
cur_weight_sum = cur_dist + cur_max - cur_min
for neighbor, weight in graph[current_vertex].items():
distance = cur_weight_sum + weight - max(weight, cur_max) + min(weight, cur_min)
if distance < ans[neighbor] or weight < cur_min:
ans[neighbor] = min(ans[neighbor], distance)
push_val = [distance, min(weight, cur_min), max(weight, cur_max)]
heapq.heappush(pq, (push_val, neighbor))
return ans[2:]
def main():
n, m = map(int, input().split(' '))
graph = defaultdict(dict)
for _ in range(m):
x,y,w = map(int, input().split(' '))
graph[x][y] = w
graph[y][x] = w
ans = calculate_distances(graph, 1, n)
print(" ".join(list(map(str, ans))))
# region fastio
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
No
| 91,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Submitted Solution:
```
a=1
```
No
| 91,154 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Submitted Solution:
```
from collections import defaultdict
import heapq
def calculate_distances(graph, starting_vertex, n):
ans = [float('inf') for i in range(n+1)]
ans[1] = 0
pq = [((0, float('inf'), float('-inf')), starting_vertex)]
while len(pq) > 0:
cur_lst, current_vertex = heapq.heappop(pq)
cur_dist, cur_min, cur_max = cur_lst
# if cur_dist > ans[current_vertex][0]:
# continue
if cur_max == float('-inf'):
cur_weight_sum = cur_dist
else:
cur_weight_sum = cur_dist + cur_max - cur_min
for neighbor, weight in graph[current_vertex].items():
distance = cur_weight_sum + weight - max(weight, cur_max) + min(weight, cur_min)
if distance < ans[neighbor] or weight < cur_min or weight > cur_max:
ans[neighbor] = min(ans[neighbor], distance)
push_val = [distance, min(weight, cur_min), max(weight, cur_max)]
heapq.heappush(pq, (push_val, neighbor))
return ans[2:]
def main():
n, m = map(int, input().split(' '))
graph = defaultdict(dict)
for _ in range(m):
x,y,w = map(int, input().split(' '))
graph[x][y] = w
graph[y][x] = w
ans = calculate_distances(graph, 1, n)
print(" ".join(list(map(str, ans))))
# region fastio
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
No
| 91,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# --------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(200000)
# import random
# from functools import reduce
# from functools import lru_cache
from heapq import *
# from collections import deque as dq
# import math
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
def judge(d, ma, mi, u, dist):
return (d <= dist[u][0]) or (d - ma <= dist[u][0] - dist[u][1]) or (d + mi <= dist[u][0] + dist[u][2])
def Dijkstra(s, n, adj):
# 注意,当边权固定时,直接使用BFS更快
# s起点,n节点个数,adj带权邻接表
dist = [(float('inf'), 0, float('inf'))] * (n + 1)
dist[s] = (0, 0, float('inf'))
heap = [(0, 0, float('inf'), s)]
while heap:
d, ma, mi, u = heappop(heap)
if not judge(d, ma, mi, u, dist): continue
for v, w in adj[u]:
nd = d + w
nmi = min(mi, w)
nma = max(ma, w)
if not judge(nd, nma, nmi, v, dist): continue
heappush(heap, (nd, nma, nmi, v))
if nd - nma + nmi < dist[v][0] - dist[v][1] + dist[v][2]:
dist[v] = (nd, nma, nmi)
return dist
n, m = RL()
adj = [[] for _ in range(n + 1)]
for _ in range(m):
u, v, w = RL()
adj[u].append((v, w))
adj[v].append((u, w))
ans = Dijkstra(1, n, adj)
print(ans)
print_list([ans[v][0] - ans[v][1] + ans[v][2] for v in range(2, n + 1)])
```
No
| 91,156 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a bipartite graph consisting of n_1 vertices in the first part, n_2 vertices in the second part, and m edges, numbered from 1 to m. You have to color each edge into one of two colors, red and blue. You have to minimize the following value: ∑ _{v ∈ V} |r(v) - b(v)|, where V is the set of vertices of the graph, r(v) is the number of red edges incident to v, and b(v) is the number of blue edges incident to v.
Sounds classical and easy, right? Well, you have to process q queries of the following format:
* 1 v_1 v_2 — add a new edge connecting the vertex v_1 of the first part with the vertex v_2 of the second part. This edge gets a new index as follows: the first added edge gets the index m + 1, the second — m + 2, and so on. After adding the edge, you have to print the hash of the current optimal coloring (if there are multiple optimal colorings, print the hash of any of them). Actually, this hash won't be verified, you may print any number as the answer to this query, but you may be asked to produce the coloring having this hash;
* 2 — print the optimal coloring of the graph with the same hash you printed while processing the previous query. The query of this type will only be asked after a query of type 1, and there will be at most 10 queries of this type. If there are multiple optimal colorings corresponding to this hash, print any of them.
Note that if an edge was red or blue in some coloring, it may change its color in next colorings.
The hash of the coloring is calculated as follows: let R be the set of indices of red edges, then the hash is (∑ _{i ∈ R} 2^i) mod 998244353.
Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
Input
The first line contains three integers n_1, n_2 and m (1 ≤ n_1, n_2, m ≤ 2 ⋅ 10^5).
Then m lines follow, the i-th of them contains two integers x_i and y_i (1 ≤ x_i ≤ n_1; 1 ≤ y_i ≤ n_2) meaning that the i-th edge connects the vertex x_i from the first part and the vertex y_i from the second part.
The next line contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries you have to process.
The next q lines contain the queries in the format introduced in the statement.
Additional constraints on the input:
* at any moment, the graph won't contain any multiple edges;
* the queries of type 2 are only asked if the previous query had type 1;
* there are at most 10 queries of type 2.
Output
To answer a query of type 1, print one integer — the hash of the optimal coloring.
To answer a query of type 2, print one line. It should begin with the integer k — the number of red edges. Then, k distinct integer should follow — the indices of red edges in your coloring, in any order. Each index should correspond to an existing edge, and the hash of the coloring you produce should be equal to the hash you printed as the answer to the previous query.
If there are multiple answers to a query, you may print any of them.
Example
Input
3 4 2
1 2
3 4
10
1 1 3
1 2 3
2
1 3 3
2
1 2 4
2
1 2 1
1 1 1
2
Output
8
8
1 3
40
2 3 5
104
3 5 6 3
104
360
4 5 6 3 8
Submitted Solution:
```
print(8)
print(8)
print(1, 3)
print(40)
print(2, 3, 5)
print(104)
print(3, 5, 6, 3)
print(104)
print(360)
print(4, 5, 6, 3, 8)
```
No
| 91,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Tags: binary search, constructive algorithms, greedy
Correct Solution:
```
from bisect import bisect,bisect_left
from collections import *
from heapq import *
from math import gcd,ceil,sqrt,floor,inf
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
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")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
class UF:#秩+路径+容量,边数
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
self.size=AI(n,1)
self.edge=A(n)
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
self.edge[pu]+=1
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
self.edge[pu]+=self.edge[pv]+1
self.size[pu]+=self.size[pv]
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
self.edge[pv]+=self.edge[pu]+1
self.size[pv]+=self.size[pu]
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return flag
def dij(s,graph):
d=AI(n,inf)
d[s]=0
heap=[(0,s)]
vis=A(n)
while heap:
dis,u=heappop(heap)
if vis[u]:
continue
vis[u]=1
for v,w in graph[u]:
if d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
#from random import randint
def check(i,j):
if not ans[i][j]:return True
for ni,nj in [[i-1,j-1],[i+1,j+1],[i+1,j-1],[i-1,j+1]]:
if 0<=ni<l and 0<=nj<l and ans[ni][nj]==ans[i][j]:
return False
return True
t=N()
for i in range(t):
m,k=RL()
a=RLL()
l=1
r=m
ma=max(a)
while l<r:
n=(l+r)>>1
if n&1:
if (3*n**2+2*n-1)//4>=m and (n+1)*n//2>=ma:
r=n
else:
l=n+1
else:
if 3*n*n//4>=m and n*n//2>=ma:
r=n
else:
l=n+1
c={}
res=[]
for i in range(k):
if a[i]:
res+=[i+1]*a[i]
c[i+1]=a[i]
res.sort(key=lambda x: -c[x])
ans=A2(l,l)
p=0
for i in range(0,l,2):
for j in range(0,l):
ans[i][j]=res[p]
p+=1
if p==len(res):break
if p==len(res):break
if p<len(res):
for i in range(1,l,2):
for j in range(0,l,2):
ans[i][j]=res[p]
p+=1
if p==len(res):break
if p==len(res):break
ci,cj=0,0
for i in range(0,l,2):
for j in range(1,l):
if not check(i,j):
ans[i][j],ans[ci][cj]=ans[ci][cj],ans[i][j]
cj+=2
if cj>=l:
cj=0
ci=ci+2
print(l)
for r in ans:
print(*r)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
```
| 91,158 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Tags: binary search, constructive algorithms, greedy
Correct Solution:
```
from random import randint
DEBUG = 0
for _ in range(int(input())):
if DEBUG:
k = randint(2, 4)
maxcnt = randint(1, 100)
cnt = [randint(1, maxcnt) for i in range(k)]
m = sum(cnt)
#print(m, k)
#print(*cnt)
cnt = sorted(enumerate(cnt), key=lambda x: -x[1])
else:
m, k = list(map(int, input().split()))
cnt = sorted(enumerate(map(int, input().split())), key=lambda x: -x[1])
l = 0
r = m
while r - l > 1:
mid = (r + l) // 2
if mid * ((mid + 1) // 2) >= cnt[0][1] and (mid // 2) ** 2 + m <= mid ** 2:
r = mid
else:
l = mid
size = r
queue = []
#for it in range((size - 1) // 4 + 1):
#queue.extend([(i, it * 4) for i in range(size)])
#if it * 4 + 2 < size:
#queue.extend([(i, it * 4 + 2) for i in range(1, size, 2)])
#for it in range((size - 1) // 4 + 1):
#if it * 4 + 2 < size:
#queue.extend([(i, it * 4 + 2) for i in range(0, size, 2)])
#queue.extend([(i, j) for i in range(0, size, 2) for j in range(1, size, 2)])
#for it in range((size - 1) // 2 + 1):
#queue.extend([(it * 2, j) for j in range(0, size, 4)])
#if it * 2 + 1 < size:
#queue.extend([(it * 2 + 1, j) for j in range(0, size, 2)])
#queue.extend([(i, j) for i in range(0, size, 2) for j in range(2, size, 4)])
#queue.extend([(i, j) for i in range(0, size, 2) for j in range(1, size, 2)])
queue.extend([(i, j) for i in range(1, size, 2) for j in range(0, size, 2)])
queue.extend([(i, j) for i in range(0, size, 2) for j in range(0, size, 4)])
queue.extend([(i, j) for i in range(0, size, 2) for j in range(2, size, 4)])
queue.extend([(i, j) for i in range(0, size, 2) for j in range(1, size, 2)])
a = [[0] * size for i in range(size)]
ind = 0
rest = cnt[ind][1]
for i, j in queue:
while not rest:
ind += 1
if ind < k:
rest = cnt[ind][1]
else:
break
else:
a[i][j] = cnt[ind][0] + 1
rest -= 1
continue
break
if not DEBUG:
print(size)
for row in a:
print(*row)
if DEBUG:
for i in range(size - 1):
for j in range(size - 1):
if a[i][j] == a[i + 1][j + 1] != 0 or a[i + 1][j] == a[i][j + 1] != 0:
print("Oops...")
print(m, k)
print(*cnt)
break
else:
continue
break
else:
continue
break
```
| 91,159 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Tags: binary search, constructive algorithms, greedy
Correct Solution:
```
from math import sqrt, ceil
import sys
def putin():
return map(int, sys.stdin.readline().split())
def sol():
m, k = putin()
A = list(putin())
A = sorted(list(enumerate(A)), reverse=True, key=lambda x: x[1])
B = []
C = []
for elem in A:
if len(B) > len(C):
C += [elem[0] + 1] * elem[1]
else:
B += [elem[0] + 1] * elem[1]
if len(C) > len(B):
C, B = B, C
even_n = ceil(max(sqrt(4 * m / 3), sqrt(2 * len(B))))
if even_n % 2 == 1:
even_n += 1
odd_n = even_n - 1
if odd_n ** 2 - (odd_n - 1) ** 2 / 4 >= m and odd_n * (odd_n + 1) / 2 >= len(B):
n = odd_n
else:
n = even_n
if n % 2 == 0:
C += [0] * (3 * n ** 2 // 4 - len(B) - len(C))
else:
C += [0] * (n ** 2 - (n - 1) ** 2 // 4 - len(B) - len(C))
if n % 2 == 0:
border = n ** 2 // 4
else:
border = (n - 1) * (n + 1) // 4
B, D = B[:border], B[border:]
D += C[border:]
C = C[:border]
B_cnt = 0
C_cnt = 0
D_cnt = 0
print(n)
for i in range(n):
for j in range(n):
if i % 2 == 1 and j % 2 == 1:
print(0, end=' ')
elif i % 2 == 1:
print(B[B_cnt], end=' ')
B_cnt += 1
elif j % 2 == 1:
print(C[C_cnt], end=' ')
C_cnt += 1
else:
print(D[D_cnt], end=' ')
D_cnt += 1
print()
for iter in range(int(sys.stdin.readline())):
sol()
```
| 91,160 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Tags: binary search, constructive algorithms, greedy
Correct Solution:
```
from math import sqrt, ceil
def sol():
m, k = map(int, input().split())
A = list(map(int, input().split()))
A = sorted(list(enumerate(A)), reverse=True, key=lambda x: x[1])
B = []
C = []
for elem in A:
if len(B) > len(C):
C += [elem[0] + 1] * elem[1]
else:
B += [elem[0] + 1] * elem[1]
if len(C) > len(B):
C, B = B, C
even_n = ceil(max(sqrt(4 * m / 3), sqrt(2 * len(B))))
if even_n % 2 == 1:
even_n += 1
odd_n = even_n - 1
if odd_n ** 2 - (odd_n - 1) ** 2 / 4 >= m and odd_n * (odd_n + 1) / 2 >= len(B):
n = odd_n
else:
n = even_n
if n % 2 == 0:
C += [0] * (3 * n ** 2 // 4 - len(B) - len(C))
else:
C += [0] * (n ** 2 - (n - 1) ** 2 // 4 - len(B) - len(C))
if n % 2 == 0:
border = n ** 2 // 4
else:
border = (n - 1) * (n + 1) // 4
B, D = B[:border], B[border:]
D += C[border:]
C = C[:border]
B_cnt = 0
C_cnt = 0
D_cnt = 0
print(n)
for i in range(n):
for j in range(n):
if i % 2 == 1 and j % 2 == 1:
print(0, end=' ')
elif i % 2 == 1:
print(B[B_cnt], end=' ')
B_cnt += 1
elif j % 2 == 1:
print(C[C_cnt], end=' ')
C_cnt += 1
else:
print(D[D_cnt], end=' ')
D_cnt += 1
print()
for iter in range(int(input())):
sol()
```
| 91,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Tags: binary search, constructive algorithms, greedy
Correct Solution:
```
from math import sqrt, ceil
for testcase_testcase in range(int(input())):
m, k = map(int, input().split());A = list(map(int, input().split()));A = sorted(list(enumerate(A)), reverse=True, key=lambda x: x[1]);B = [];C = []
for elem in A:
if len(B) > len(C): C += [elem[0] + 1] * elem[1]
else: B += [elem[0] + 1] * elem[1]
if len(C) > len(B):C, B = B, C
even_n = ceil(max(sqrt(4 * m / 3), sqrt(2 * len(B))))
if even_n % 2 == 1:even_n += 1
odd_n = even_n - 1;n = (odd_n if odd_n ** 2 - (odd_n - 1) ** 2 / 4 >= m and odd_n * (odd_n + 1) / 2 >= len(B) else even_n)
C += ([0] * (3 * n ** 2 // 4 - len(B) - len(C)) if n % 2 == 0 else [0] * (n ** 2 - (n - 1) ** 2 // 4 - len(B) - len(C)))
border = (n ** 2 // 4 if n % 2 == 0 else (n - 1) * (n + 1) // 4);B, D = B[:border], B[border:];D += C[border:];C = C[:border];B_cnt = 0;C_cnt = 0;D_cnt = 0;print(n)
for i in range(n):
for j in range(n):
if i % 2 == 1 and j % 2 == 1: print(0, end=' ')
elif i % 2 == 1:print(B[B_cnt], end=' ');B_cnt += 1
elif j % 2 == 1:print(C[C_cnt], end=' ');C_cnt += 1
else:print(D[D_cnt], end=' ');D_cnt += 1
print()
```
| 91,162 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Tags: binary search, constructive algorithms, greedy
Correct Solution:
```
def cheak(x):
return x**2-(x//2)**2>=m and x*(x//2+(1 if x%2!=0 else 0))>=mx
for test in range(int(input())):
m,k=(int(i) for i in input().split())
a=[int(i) for i in input().split()]
mx=max(a)
z=0;y=m*4
while z!=y:
x=(z+y)//2
if cheak(x):
y=x
else:
z=x+1
else:
x=z
a=sorted(list(map(list,zip(a,range(1,len(a)+1)))))
def get():
i=len(a)
while i!=0:
i-=1
while a[i][0]>0:
a[i][0]-=1
yield a[i][1]
yield 0
mt=[[0 for i in range(x)] for j in range(x)]
t=1
it=get()
for i in range(0,x,2):
if t==0:break
for j in range(1,x,2):
t=next(it)
if t:mt[i][j]=t
else:break
for i in range(0,x,2):
if t==0:break
for j in range(0,x,2):
t=next(it)
if t:mt[i][j]=t
else:break
for i in range(1,x,2):
if t==0:break
for j in range(0,x,2):
t=next(it)
if t:mt[i][j]=t
else:break
print(len(mt))
for i in mt:
print(*i)
```
| 91,163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Tags: binary search, constructive algorithms, greedy
Correct Solution:
```
from math import ceil
import heapq
def solve(m,k,a):
N = 1
free = ceil(N/2)**2
A = (N//2)*ceil(N/2)
B = (N//2)*ceil(N/2)
while free + A + B < m:
N += 1
free = ceil(N/2)**2
A = (N//2)*ceil(N/2)
B = (N//2)*ceil(N/2)
mx_freq = max(a)
while free + B < mx_freq:
N += 1
free = ceil(N/2)**2
A = (N//2)*ceil(N/2)
B = (N//2)*ceil(N/2)
ans = [[0]*N for _ in range(N)]
A = [(i,j) for i in range(1,N,2) for j in range(0,N,2)]
B = [(i,j) for i in range(0,N,2) for j in range(1,N,2)]
F = [(i,j) for i in range(0,N,2) for j in range(0,N,2)]
pq = []
for i in range(k):
if a[i] > 0:
heapq.heappush(pq,(-a[i],i+1))
l = len(pq)
cur_ele = None
cur_freq = 0
while B:
if not pq and cur_freq == 0:
break
if cur_freq == 0:
X = heapq.heappop(pq)
cur_ele = X[1]
cur_freq = -X[0]
i,j = B.pop()
ans[i][j] = cur_ele
cur_freq -= 1
later = []
if len(pq) == l-1:
later.append([cur_ele,cur_freq])
cur_ele = None
cur_freq = 0
while A:
if not pq and cur_freq == 0:
break
if cur_freq == 0:
X = heapq.heappop(pq)
cur_ele = X[1]
cur_freq = -X[0]
i,j = A.pop()
ans[i][j] = cur_ele
cur_freq -= 1
if later:
ele,freq = later.pop()
if cur_freq:
heapq.heappush(pq,(-cur_freq,cur_ele))
cur_ele = ele
cur_freq = freq
while pq or cur_freq:
if cur_freq == 0:
X = heapq.heappop(pq)
cur_ele = X[1]
cur_freq = -X[0]
while cur_freq:
i,j = F.pop()
ans[i][j] = cur_ele
cur_freq -= 1
print(N)
for row in ans:
print(*row)
return -1
for nt in range(int(input())):
m,k = map(int,input().split())
a = list(map(int,input().split()))
solve(m,k,a)
```
| 91,164 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Tags: binary search, constructive algorithms, greedy
Correct Solution:
```
from math import sqrt, ceil
for iter in range(int(input())):
m, k = map(int, input().split());A = list(map(int, input().split()));A = sorted(list(enumerate(A)), reverse=True, key=lambda x: x[1]);B = [];C = []
for elem in A:
if len(B) > len(C): C += [elem[0] + 1] * elem[1]
else: B += [elem[0] + 1] * elem[1]
if len(C) > len(B):C, B = B, C
even_n = ceil(max(sqrt(4 * m / 3), sqrt(2 * len(B))))
if even_n % 2 == 1:
even_n += 1
odd_n = even_n - 1
if odd_n ** 2 - (odd_n - 1) ** 2 / 4 >= m and odd_n * (odd_n + 1) / 2 >= len(B):
n = odd_n
else:
n = even_n
if n % 2 == 0:
C += [0] * (3 * n ** 2 // 4 - len(B) - len(C))
else:
C += [0] * (n ** 2 - (n - 1) ** 2 // 4 - len(B) - len(C))
if n % 2 == 0:
border = n ** 2 // 4
else:
border = (n - 1) * (n + 1) // 4
B, D = B[:border], B[border:]
D += C[border:]
C = C[:border]
B_cnt = 0
C_cnt = 0
D_cnt = 0
print(n)
for i in range(n):
for j in range(n):
if i % 2 == 1 and j % 2 == 1: print(0, end=' ')
elif i % 2 == 1:print(B[B_cnt], end=' ');B_cnt += 1
elif j % 2 == 1:print(C[C_cnt], end=' ');C_cnt += 1
else:print(D[D_cnt], end=' ');D_cnt += 1
print()
```
| 91,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Submitted Solution:
```
def cheak(x):
return x**2-(x//2)**2>=m and x*(x//2+(1 if x%2!=0 else 0))>=mx
for test in range(int(input())):
m,k=(int(i) for i in input().split())
a=[int(i) for i in input().split()]
mx=max(a)
z=0;y=m*4
while z!=y:
x=(z+y)//2
if cheak(x):
y=x
else:
z=x+1
else:
x=z
a=sorted(list(map(list,zip(a,range(1,len(a)+1)))))
def get():
i=len(a)
while i!=0:
i-=1
while a[i][0]>0:
a[i][0]-=1
yield a[i][1]
return 0
mt=[[0 for i in range(x)] for j in range(x)]
t=1
it=get()
try:
for i in range(0,x,2):
if t==0:break
for j in range(0,x,2):
t=next(it)
if t:mt[i][j]=t
else:break
for i in range(0,x,2):
if t==0:break
for j in range(1,x,2):
t=next(it)
if t:mt[i][j]=t
else:break
for i in range(1,x,2):
if t==0:break
for j in range(0,x,2):
t=next(it)
if t:mt[i][j]=t
else:break
except StopIteration:...
for i in mt:
print(*i)
```
No
| 91,166 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Submitted Solution:
```
# 6fbbb444ee015ce84ca315f20e46e28a71024d21eb5e2c6477de2b0972b44556
print('hello')
```
No
| 91,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Submitted Solution:
```
from bisect import bisect,bisect_left
from collections import *
from heapq import *
from math import gcd,ceil,sqrt,floor,inf
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
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")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
class UF:#秩+路径+容量,边数
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
self.size=AI(n,1)
self.edge=A(n)
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
self.edge[pu]+=1
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
self.edge[pu]+=self.edge[pv]+1
self.size[pu]+=self.size[pv]
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
self.edge[pv]+=self.edge[pu]+1
self.size[pv]+=self.size[pu]
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return flag
def dij(s,graph):
d=AI(n,inf)
d[s]=0
heap=[(0,s)]
vis=A(n)
while heap:
dis,u=heappop(heap)
if vis[u]:
continue
vis[u]=1
for v,w in graph[u]:
if d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
#from random import randint
t=N()
for i in range(t):
m,k=RL()
a=RLL()
l=1
r=m
ma=max(a)
while l<r:
n=(l+r)>>1
if n&1:
if (3*n**2+2*n-1)//4>=m and (n+1)*n//2>=ma:
r=n
else:
l=n+1
else:
if 3*n*n//4>=m and n*n//2>=ma:
r=n
else:
l=n+1
c={}
res=[]
for i in range(k):
if a[i]:
res+=[i+1]*a[i]
c[i+1]=a[i]
res.sort(key=lambda x: -c[x])
ans=A2(l,l)
p=0
for i in range(0,l,2):
for j in range(0,l):
ans[i][j]=res[p]
p+=1
if p==len(res):break
if p==len(res):break
if p<len(res):
for i in range(1,l,2):
for j in range(0,l,2):
ans[i][j]=res[p]
p+=1
if p==len(res):break
if p==len(res):break
print(l)
for r in ans:
print(*r)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
```
No
| 91,168 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let a_i be how many numbers i (1 ≤ i ≤ k) you have.
An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:
1. The number of occupied cells doesn't exceed 3;
2. The numbers on each diagonal are distinct.
Make a beautiful matrix of minimum size.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.
The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.
It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.
Output
For each t test case print a single integer n — the size of the beautiful matrix.
In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.
Example
Input
2
3 4
2 0 0 1
15 4
2 4 8 1
Output
2
4 1
0 1
5
3 0 0 2 2
3 2 3 3 0
0 1 0 4 0
3 0 0 0 0
2 1 3 3 3
Note
Note that 0 in this problem represents a blank, not a number.
Examples of possible answers for the first test case:
\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}
Examples of not beautiful matrices for the first test case:
\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}
The example of the not beautiful matrix for the second test case:
\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}
Everything is okay, except the left-top submatrix contains 4 numbers.
Submitted Solution:
```
#!/usr/bin/env python3
# set vim: fdm=marker sw=4 ts=4 et
from collections import defaultdict
from collections import deque
def get_matrix(n, a):
b = []
for i in range(n):
b.append([0] * n)
for i in range(0, n, 2):
for j in range(n):
b[i][j] = a[-1][1]
a[-1][0] -= 1
if a[-1][0] == 0:
a.pop()
if len(a) == 0:
return b
for i in range(1, n, 2):
for j in range(0, n, 2):
b[i][j] = a[-1][1]
a[-1][0] -= 1
if a[-1][0] == 0:
a.pop()
if len(a) == 0:
return b
return b
for _ in range(int(input())):
m, k = map(int, input().split())
a = [int(i) for i in input().split()]
a = [[a[i], i + 1] for i in range(len(a)) if a[i] != 0]
a.sort()
max_a_i = a[-1][0]
# print('max_a_i', max_a_i)
# print('m', m)
# n * ((n + 1) // 2)
# 2 -> 2
# 3 -> 6
# 4 -> 8
# 5 -> 15
l, r = (0, 1000)
while r - l > 1:
m1 = (l + r) // 2
# print('m1', m1)
m2 = m1 * ((m1 + 1) // 2)
# print('m2', m2)
m3 = m2 + (m1 // 2 * (m1 + 1) // 2)
# print('m3', m3)
if m2 >= max_a_i and m3 >= m:
r = m1
else:
l = m1
n = r
a2 = []
for a_i in a:
a2.append(a_i[:])
b = get_matrix(n, a)
valid = True
for i in range(1, n):
for j in range(n):
if j > 0 and b[i - 1][j - 1] == b[i][j]:
valid = False
break
if j < n - 1 and b[i - 1][j + 1] == b[i][j]:
valid = False
break
if not valid:
break
if not valid:
b = get_matrix(n + 1, a2)
print(n)
for i in range(n):
print(' '.join(map(str, b[i])))
```
No
| 91,169 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Tags: binary search, bitmasks, brute force, dp, strings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
s = input()[:-1]
left, right = 0, n
while left < right:
mid = right - (right - left) // 2
A = [[0] * (n + 2) for _ in range(k)]
for c in range(k):
A[c][n] = A[c][n + 1] = n + 1
L = 0
for i in range(n - 1, -1, -1):
if s[i] == '?' or ord(s[i]) - ord('a') == c: L += 1
else: L = 0
A[c][i] = i + mid if L >= mid else A[c][i + 1]
dp = [n + 1] * (1 << k)
dp[0] = 0
for mask in range(1 << k):
for i in range(k):
if mask >> k & 1: continue
t = mask | 1 << i
dp[t] = min(dp[t], A[i][dp[mask]])
if dp[-1] <= n: left = mid
else: right = mid - 1
print(left)
```
| 91,170 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Tags: binary search, bitmasks, brute force, dp, strings, two pointers
Correct Solution:
```
import sys;input = sys.stdin.readline;n, k = map(int, input().split());s = input()[:-1];left, right = 0, n
while left < right:
mid = right - (right - left) // 2;A = [[0] * (n + 2) for _ in range(k)]
for c in range(k):
A[c][n] = A[c][n + 1] = n + 1;L = 0
for i in range(n - 1, -1, -1):L = (L + 1 if s[i] == '?' or ord(s[i]) - ord('a') == c else 0);A[c][i] = i + mid if L >= mid else A[c][i + 1]
dp = [n + 1] * (1 << k);dp[0] = 0
for mask in range(1 << k):
for i in range(k):
if mask >> k & 1: continue
t = mask | 1 << i;dp[t] = min(dp[t], A[i][dp[mask]])
if dp[-1] <= n: left = mid
else: right = mid - 1
print(left)
```
| 91,171 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Tags: binary search, bitmasks, brute force, dp, strings, two pointers
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
accu = 0
index = inf
for i in range(n)[::-1]:
if s[i]==ord('?') or s[i]==97+j:
accu += 1
else:
accu = 0
if accu>=needed:
index = i + needed
effect[j][i] = index
effect[j][i] = min(effect[j][i+4-4],effect[j][i+3-3],inf)
# print(effect)
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
| 91,172 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Tags: binary search, bitmasks, brute force, dp, strings, two pointers
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
accu = 0
index = inf
for i in range(n)[::-1]:
if s[i]==ord('?') or s[i]==97+j:
accu += 1
else:
accu = 0
if accu>=needed:
index = i + needed
# print(j,i,accu)
effect[j][i] = index
# print(effect)
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
| 91,173 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Tags: binary search, bitmasks, brute force, dp, strings, two pointers
Correct Solution:
```
N, K = list(map(int, input().split()))
S = input().strip()
S = [-1 if _ == '?' else ord(_) - ord('a') for _ in S]
def check(x):
p = [[N for i in range(N+1)] for k in range(K)]
for k in range(K):
keep = 0
for i in range(N-1, -1, -1):
keep += 1
if S[i] != -1 and S[i] != k:
keep = 0
p[k][i] = p[k][i+1]
if keep >= x:
p[k][i] = i + x - 1
d = [N for s in range(1<<K)]
d [0] = -1
for s in range(1, 1<<K):
for k in range(K):
if (s&(1<<k)) and (d[s^(1<<k)]<N):
d[s] = min(d[s], p[k][d[s^(1<<k)]+1])
# print('d[%d%d]=%d'%(s//2, s%2, d[s]))
return d[(1<<K)-1] < N
l, r = 0, N//K
while l < r:
mid = (l + r + 1) // 2
if check(mid):
l = mid
else:
r = mid - 1
print(l)
```
| 91,174 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Tags: binary search, bitmasks, brute force, dp, strings, two pointers
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
accu = 0
index = inf
for i in range(n)[::-1]:
if s[i]==ord('?') or s[i]==97+j:
accu += 1
else:
accu = 0
if accu>=needed:
index = i + needed
effect[j][i] = index
# effect[j][i] = min(effect[j][i],inf*inf+inf*inf)
# print(effect)
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
| 91,175 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Tags: binary search, bitmasks, brute force, dp, strings, two pointers
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
accu = 0
index = inf
for i in range(n)[::-1]:
if s[i]==ord('?') or s[i]==97+j:
accu += 1
else:
accu = 0
if accu>=needed:
index = i + needed
effect[j][i] = index
effect[j][i] = min(effect[j][i],inf)
# print(effect)
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
| 91,176 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Tags: binary search, bitmasks, brute force, dp, strings, two pointers
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N, K = map(int, input().split())
S = [-1 if a == "?" else ord(a) - 97 for a in input()]
II = {1 << i: i for i in range(20)}
def calc(mmm):
inf = 300000
X = [[0] * N for _ in range(K)]
for k in range(K):
Xk = X[k]
mi = inf
r = 0
for i in range(N)[::-1]:
if S[i] < 0 or S[i] == k:
r += 1
else:
r = 0
if r >= mmm:
mi = min(mi, i + mmm)
Xk[i] = mi
Y = [0] * (1 << K)
for i in range(1, 1 << K):
mi = inf
for j in range(K):
if i >> j & 1:
ii = i ^ (1 << j)
if Y[ii] < N:
mi = min(mi, X[j][Y[ii]])
Y[i] = mi
return 1 if Y[-1] < inf else 0
l, r = 0, N // K + 1
while r - l > 1:
m = l + r >> 1
if calc(m):
l = m
else:
r = m
print(l)
```
| 91,177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Submitted Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
maxconseq = [[0 for j in range(k)] for i in range(n+1)]
for i in range(n):
if s[i]==ord('?'):
for j in range(k):
maxconseq[i][j] = maxconseq[i-1][j] + 1
else:
j = s[i]-97
maxconseq[i][j] = maxconseq[i-1][j] + 1
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
for i in range(n)[::-1]:
if maxconseq[i][j]>=needed:
effect[j][i-needed+1] = i+1
effect[j][i] = min(effect[j][i], effect[j][i+1])
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
Yes
| 91,178 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Submitted Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.size = n
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
if r==self.size:
r = self.num
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
N,K = mi()
S = input()
S = [ord(S[i])-ord("a") for i in range(N)]
pow_2 = [pow(2,i) for i in range(K)]
k = K
def cond(n):
cnt = [0 for i in range(k)]
v = 0
for i in range(n):
if not 0<= S[i] < k:
continue
if cnt[S[i]]==0:
v += 1
cnt[S[i]] += 1
str_range = [[N for j in range(N)] for i in range(k)]
if v==1:
for i in range(k):
if cnt[i]:
str_range[i][0] = 0
elif v==0:
for i in range(k):
str_range[i][0] = 0
for i in range(n,N):
if 0 <= S[i-n] < k:
cnt[S[i-n]] -= 1
if cnt[S[i-n]] == 0:
v -= 1
if 0 <= S[i] < k:
cnt[S[i]] += 1
if cnt[S[i]] == 1:
v += 1
if v==1:
for j in range(k):
if cnt[j]:
for l in range(i-n+1,-1,-1):
if str_range[j][l] == N:
str_range[j][l] = i - n + 1
else:
break
break
elif v==0:
for j in range(k):
for l in range(i-n+1,-1,-1):
if str_range[j][l] == N:
str_range[j][l] = i - n + 1
else:
break
INF = N + 1
dp = [INF for bit in range(1<<k)]
dp[0] = 0
for bit in range(1<<k):
if dp[bit]>=N:
continue
idx = dp[bit]
for i in range(k):
if not bit >> i & 1:
nv = bit|pow_2[i]
tmp = str_range[i][idx] + n
dp[nv] = min(dp[nv],tmp)
return dp[-1]!=INF
ok = 0
ng = N+1
while ng-ok>1:
mid = (ok+ng)//2
if cond(mid):
ok = mid
else:
ng = mid
print(ok)
```
Yes
| 91,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Submitted Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
accu = 0
index = inf
for i in range(n)[::-1]:
if s[i]==ord('?') or s[i]==97+j:
accu += 1
else:
accu = 0
if accu>=needed:
index = i + needed
effect[j][i] = index
effect[j][i] = min(effect[j][i+4-4],effect[j][i+3-3],inf*inf)
# print(effect)
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
Yes
| 91,180 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Submitted Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
accu = 0
index = inf
for i in range(n)[::-1]:
if s[i]==ord('?') or s[i]==97+j:
accu += 1
else:
accu = 0
if accu>=needed:
index = i + needed
effect[j][i] = index
effect[j][i] = effect[j][i+4-4]
# print(effect)
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
Yes
| 91,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Submitted Solution:
```
from collections import deque
import bisect
n, k = map(int,input().split())
s = input()
n=200000
k=15
s = "?"*200000
effectj = [[] for i in range(1<<k)]
for state in range(1<<k):
for j in range(k):
if (1<<j) & state>0: effectj[state].append(j)
maxconseq = [[0 for j in range(k)] for i in range(n+1)]
for i in range(n):
if s[i]=='?':
for j in range(k):
maxconseq[i][j] = maxconseq[i-1][j] + 1
else:
j = ord(s[i])-97
maxconseq[i][j] = maxconseq[i-1][j] + 1
#print(maxconseq)
def judge(needed):
minstate = [2147483647]*(1<<k)
minstate[0] = -1
effect = [[] for i in range(k)]
for i in range(n):
for j in range(k):
if maxconseq[i][j]>=needed: effect[j].append(i)
for state in range(1<<k):
for j in effectj[state]:
if effect[j] and minstate[state-(1<<j)] + needed > effect[j][-1]: continue
loc = bisect.bisect_left(effect[j], minstate[state-(1<<j)] + needed)
minstate[state] = min(minstate[state], effect[j][loc])
if minstate[-1]<n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
No
| 91,182 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Submitted Solution:
```
from collections import deque
import bisect
#n, k = map(int,input().split())
#s = input()
n=200000
k=12
s = "?"*200000
maxconseq = [[0 for j in range(k)] for i in range(n+1)]
for i in range(n):
if s[i]=='?':
for j in range(k):
maxconseq[i][j] = maxconseq[i-1][j] + 1
else:
j = ord(s[i])-97
maxconseq[i][j] = maxconseq[i-1][j] + 1
#print(maxconseq)
def judge(needed):
minstate = [2147483647]*(1<<k)
minstate[0] = -1
effect = [[] for i in range(k)]
for i in range(n):
for j in range(k):
if maxconseq[i][j]>=needed: effect[j].append(i)
for state in range(1<<k):
for j in range(k):
if (1<<j) & state==0: continue
loc = bisect.bisect_left(effect[j], minstate[state-(1<<j)] + needed)
if loc == len(effect[j]): continue
minstate[state] = min(minstate[state], effect[j][loc])
if minstate[-1]<n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
No
| 91,183 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Submitted Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
accu = 0
index = inf
for i in range(n)[::-1]:
if s[i]==ord('?') or s[i]==97+j:
accu += 1
else:
accu = 1
if accu>=needed:
index = i + needed
effect[j][i] = index
# print(effect)
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
No
| 91,184 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.
You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.
Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.
The value of a string s is the minimum value among f_i for all i from 1 to k.
What is the maximum value the string can have?
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.
The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.
Output
Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.
Examples
Input
10 2
a??ab????b
Output
4
Input
9 4
?????????
Output
2
Input
2 3
??
Output
0
Input
15 3
??b?babbc??b?aa
Output
3
Input
4 4
cabd
Output
1
Note
In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.
In the second example one of the possible strings is "aabbccdda".
In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
Submitted Solution:
```
from collections import deque
import bisect
#n, k = map(int,input().split())
#s = input()
n=200000
k=10
s = "?"*200000
maxconseq = [[0 for j in range(k)] for i in range(n+1)]
for i in range(n):
if s[i]=='?':
for j in range(k):
maxconseq[i][j] = maxconseq[i-1][j] + 1
else:
j = ord(s[i])-97
maxconseq[i][j] = maxconseq[i-1][j] + 1
#print(maxconseq)
def judge(needed):
minstate = [2147483647]*(1<<k)
minstate[0] = -1
effect = [[] for i in range(k)]
for i in range(n):
for j in range(k):
if maxconseq[i][j]>=needed: effect[j].append(i)
for state in range(1<<k):
for j in range(k):
if (1<<j) & state==0: continue
loc = bisect.bisect_left(effect[j], minstate[state-(1<<j)] + needed)
if loc == len(effect[j]): continue
minstate[state] = min(minstate[state], effect[j][loc])
if minstate[-1]<n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
```
No
| 91,185 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Tags: number theory
Correct Solution:
```
def isPrime(num):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
return False
break
else:
return True
else:
return False
def RectangularGame(n):
sum = n
if n==1:
return 1
else:
if isPrime(n):
return n+1
else:
for i in range(2,n):
if n%i == 0:
sum = sum + RectangularGame(n//i)
return sum
else:
continue
number = int(input())
print(RectangularGame(number))
```
| 91,186 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Tags: number theory
Correct Solution:
```
n = int(input())
sum = n
while n%2 == 0:
n = n//2
sum = sum + n
i = 3
while i<=int(n**0.5):
while n%i == 0:
n=n//i
sum = sum + n
i = i + 2
if n > 2:
sum = sum + 1
print(sum)
```
| 91,187 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Tags: number theory
Correct Solution:
```
a=int(input())
c=a
while(a>1):
for i in range(1000000000):
if(a%(i+2)==0):
c+=(a/(i+2))
a=a/(i+2)
break
c=int(c)
print(c)
```
| 91,188 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Tags: number theory
Correct Solution:
```
n=int(input())
sum=n
while n!=1:
for i in range(2,n+1):
if n%i==0:
n//=i
break
sum+=n
print(sum)
```
| 91,189 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Tags: number theory
Correct Solution:
```
n=int(input())
sum=n
b=0
while(b!=1):
for i in range(2,n+1):
if(n%i==0):
b=n//i
break
sum=sum+b
n=b
print(sum)
```
| 91,190 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Tags: number theory
Correct Solution:
```
N = int(input())
sum = N
for j in range(2,N+1):
while N % j == 0:
N //= j
sum += N
print(sum)
```
| 91,191 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Tags: number theory
Correct Solution:
```
def maxsum(n):
ans = 0
while(n>1):
ans+=n
for i in range(2,n+1):
if n%i == 0:
n = n//i
break
return ans+1
n = int(input())
print(maxsum(n))
```
| 91,192 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Tags: number theory
Correct Solution:
```
n=int(input())
b = 0
sum=n
while b!=1:
for i in range(2,n+1):
if i==n:
b=1
break
if n%i==0:
a=i
b=int(n/a)
break
sum=sum+b
n=b
print(sum)
```
| 91,193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Submitted Solution:
```
import math
primes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,
61,67,71,73,79,83,89,97,101,103,107,109,113,127,
131,137,139,149,151,157,163,167,173,179,181,191,
193,197,199,211,223,227,229,233,239,241,251,257,
263,269,271,277,281,293, 307, 311, 313, 317, 331, 337, 347, 349,
353,359 ,367,373,379,383,389,397,401,409,419, 421, 431 ,433 ,439 ,443 ,449 ,457 ,461 ,463
,467 ,479 ,487 ,491 ,499 ,503 ,509 ,521 ,523 ,541
,547 ,557 ,563 ,569 ,571 ,577 ,587 ,593 ,599 ,601
,607 ,613 ,617 ,619 ,631 ,641 ,643 ,647 ,653 ,659
,661 ,673 ,677 ,683 ,691 ,701 ,709 ,719 ,727 ,733
,739 ,743 ,751 ,757 ,761 ,769 ,773 ,787 ,797 ,809
,811 ,821 ,823 ,827 ,829 ,839 ,853 ,857 ,859 ,863
,877 ,881 ,883 ,887 ,907 ,911 ,919 ,929 ,937 ,941
,947 ,953 ,967 ,971 ,977 ,983 ,991 ,997 ,1009 ,1013
,1019 ,1021 ,1031 ,1033 ,1039 ,1049 ,1051 ,1061 ,1063, 1069
,1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151
,1153, 1163, 1171, 1181,11897,36709, 1187, 1193, 1201, 1213, 1217,31607]
n=int(input())
tot=n
for i in range(len(primes)):
while n%primes[i]==0:
tot+=n//primes[i]
n=n//primes[i]
if n==1:
print(tot)
else:
print(tot+1)
```
Yes
| 91,194 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Submitted Solution:
```
import math
def f(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return n // i
return 1
n = int(input())
ans, b = n, n
while b != 1:
b = f(b)
ans += b
print(ans)
```
Yes
| 91,195 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Submitted Solution:
```
import math
n = int(input())
result = 0
num = 2
sqrt_n = math.sqrt(n)
result += n
while num <= sqrt_n:
if n % num == 0:
result += n // num
n //= num
sqrt_n = math.sqrt(n)
num = 1
num += 1
result += 1
print(result)
```
Yes
| 91,196 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Submitted Solution:
```
n=int(input())
ans=n
while n>1:
f=0
for ff in range(2,n):
if n%ff==0:
f=max(f,max(ff,n//ff))
if f==0:
ans+=1
break
ans+=f
n=f
print(ans)
```
Yes
| 91,197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Submitted Solution:
```
n = int(input())
c = n-1
while c > 1:
s = 0
for i in range(2, n + 1):
if n % i == 0:
c += (n // i)
n = n // i
s = 1
break
if s == 0:
c += 1
break
print(c)
```
No
| 91,198 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Submitted Solution:
```
def hcf(x,y):
if x > y:
smaller = y
else:
smaller=x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
c=10
A=[]
p=10
n=int(input())
for i in range(n-1,0,-1):
if n%i==0:
A.append(i)
for i in range(len(A)):
p=hcf(A[i],p)
if p!=1:
c+=p
else:
if i==len(A)-1:
c+=p
else:
continue
print(c)
```
No
| 91,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.