message stringlengths 2 45.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 254 108k | cluster float64 3 3 | __index_level_0__ int64 508 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m.
The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate.
Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.
Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.
For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The first line of each testcase contains two integers n and m (1 β€ n β€ 3 β
10^5; 2 β€ m β€ 10^8) β the number of robots and the coordinate of the right wall.
The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β the starting coordinates of the robots.
The third line of each testcase contains n space-separated characters 'L' or 'R' β the starting directions of the robots ('L' stands for left and 'R' stands for right).
All coordinates x_i in the testcase are distinct.
The sum of n over all testcases doesn't exceed 3 β
10^5.
Output
For each testcase print n integers β for the i-th robot output the time it explodes at if it does and -1 otherwise.
Example
Input
5
7 12
1 2 3 4 9 10 11
R R L L R R R
2 10
1 6
R R
2 10
1 3
L L
1 10
5
R
7 8
6 1 7 2 3 5 4
R L R L L L L
Output
1 1 1 1 2 -1 2
-1 -1
2 2
-1
-1 2 7 3 2 7 3
Note
Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase:
<image>
Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer.
After second 3 robot 6 just drive infinitely because there's no robot to collide with.
Submitted Solution:
```
def bs(l,k):
if len(l)>0:
lo = 0
hi = len(l)-1
while hi > lo:
mid = (lo+hi)//2
if l[mid][1] >= k:
hi = mid
else:
lo = mid+1
index = lo
if l[lo][1] < k:
index += 1
return index
else:
return 0
for _ in range(int(input())):
N,M = map(int,input().split())
a = list(map(int,input().split()))
L = [[],[]]
R = [[],[]]
d = input().split()
for i in range(N):
x = a[i]
j = 0
if x%2 != 0:
j += 1
if d[i] == "L":
L[j].append((i,x))
else:
R[j].append((i,x))
# for i in range(2):
# L[i].sort(key= lambda a:a[1])
# R[i].sort(key= lambda a:a[1])
L1 = [[],[]]
R1 = [[],[]]
output = []
for i in range(2):
for a in L[i]:
r = bs(R[i],a[1])
if r > 0:
b = R[i].pop(r-1)
t = (a[1]-b[1])//2
output.append((a[0],t))
output.append((b[0],t))
else:
L1[i].append(a)
R1[i]=R[i]
for i in range(2):
while len(L1[i])>1:
a = L1[i].pop(0)
b = L1[i].pop(0)
t = (a[1]+b[1])//2
output.append((a[0],t))
output.append((b[0],t))
while len(R1[i])>1:
a = R1[i].pop()
b = R1[i].pop()
t = M-((a[1]+b[1])//2)
output.append((a[0],t))
output.append((b[0],t))
for i in range(2):
if len(L1[i]) > 0 and len(R1[i]) > 0:
a = L1[i].pop()
b = R1[i].pop()
t = (((2*M)+a[1]-b[1])//2)
output.append((a[0],t))
output.append((b[0],t))
for i in range(2):
for a in L1[i]:
output.append((a[0],-1))
for a in R1[i]:
output.append((a[0],-1))
output.sort(key=lambda a:a[0])
for e in output[:-1]:
print(e[1],end=" ")
print(output[-1][1])
``` | instruction | 0 | 88,669 | 3 | 177,338 |
No | output | 1 | 88,669 | 3 | 177,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m.
The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate.
Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.
Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.
For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The first line of each testcase contains two integers n and m (1 β€ n β€ 3 β
10^5; 2 β€ m β€ 10^8) β the number of robots and the coordinate of the right wall.
The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β the starting coordinates of the robots.
The third line of each testcase contains n space-separated characters 'L' or 'R' β the starting directions of the robots ('L' stands for left and 'R' stands for right).
All coordinates x_i in the testcase are distinct.
The sum of n over all testcases doesn't exceed 3 β
10^5.
Output
For each testcase print n integers β for the i-th robot output the time it explodes at if it does and -1 otherwise.
Example
Input
5
7 12
1 2 3 4 9 10 11
R R L L R R R
2 10
1 6
R R
2 10
1 3
L L
1 10
5
R
7 8
6 1 7 2 3 5 4
R L R L L L L
Output
1 1 1 1 2 -1 2
-1 -1
2 2
-1
-1 2 7 3 2 7 3
Note
Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase:
<image>
Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer.
After second 3 robot 6 just drive infinitely because there's no robot to collide with.
Submitted Solution:
```
for _ in range(int(input())):
n,m=map(int,input().split())
a=list(map(int,input().split()))
pos=list(map(str,input().split()))
even=[]
odd=[]
for i in range(n):
if a[i]%2==0:
even.append([a[i],pos[i],i])
else:
odd.append([a[i],pos[i],i])
even.sort()
odd.sort()
ans=[-1]*n
if len(even)>1:
stack=[even[0]]
for i in range(1,len(even)-1):
now=even[i][1]
try:
curr=stack[-1][1]
except:
stack.append(even[i])
continue
if curr==now and curr=="R":
stack.append(even[i])
elif curr==now and curr=="L":
t=abs((stack[-1][0]+even[i][0])//2)
ans[stack[-1][2]]=t
ans[even[i][2]]=t
stack.pop()
elif curr=="R" and now=="L":
t=abs((stack[-1][0]-even[i][0])//2)
ans[stack[-1][2]] = t
ans[even[i][2]] = t
stack.pop()
elif curr=="L" and now=="R":
if len(stack)==1:
stack.append(even[i])
else:
t = abs((stack[-1][0] - stack[-2][0]) // 2)
ans[stack[-1][2]] = t
ans[stack[-2][2]] = t
stack.pop()
stack.append(even[i])
if len(stack)>0 and len(even)>1:
if stack[-1][1]=="L" and even[-1][1]=="L":
t = abs((stack[-1][0] + even[-1][0]) // 2)
ans[stack[-1][2]] = t
ans[even[-1][2]] = t
elif stack[-1][1]=="R" and even[-1][1]=="L":
t = abs((stack[-1][0] - even[-1][0]) // 2)
ans[stack[-1][2]] = t
ans[even[-1][2]] = t
elif stack[-1][1]=="L" and even[-1][1]=="R":
t = m-abs((stack[-1][0] - even[-1][0]) // 2)
ans[stack[-1][2]] = t
ans[even[-1][2]] = t
elif stack[-1][1]=="R" and even[-1][1]=="R":
t=m-abs((stack[-1][0]+even[-1][0])//2)
ans[stack[-1][2]] = t
ans[even[-1][2]] = t
stack.pop()
while len(stack)>1:
t = m - abs((stack[-1][0] + stack[-2][0]) // 2)
ans[stack[-1][2]] = t
ans[stack[-2][2]] = t
stack.pop()
if len(odd)>1:
stack=[odd[0]]
for i in range(1,len(odd)-1):
now=odd[i][1]
try:
curr=stack[-1][1]
except:
stack.append(odd[i])
continue
if curr==now and curr=="R":
stack.append(odd[i])
elif curr==now and curr=="L":
t=abs((stack[-1][0]+odd[i][0])//2)
ans[stack[-1][2]]=t
ans[odd[i][2]]=t
stack.pop()
elif curr=="R" and now=="L":
t=abs((stack[-1][0]-odd[i][0])//2)
ans[stack[-1][2]] = t
ans[odd[i][2]] = t
stack.pop()
elif curr=="L" and now=="R":
if len(stack)==1:
stack.append(odd[i])
else:
t = abs((stack[-1][0] - stack[-2][0]) // 2)
ans[stack[-1][2]] = t
ans[stack[-2][2]] = t
stack.pop()
stack.append(odd[i])
if len(stack)>0 and len(odd)>1:
if stack[-1][1]=="L" and odd[-1][1]=="L":
t = abs((stack[-1][0] + odd[-1][0]) // 2)
ans[stack[-1][2]] = t
ans[odd[-1][2]] = t
elif stack[-1][1]=="R" and odd[-1][1]=="L":
t = abs((stack[-1][0] - odd[-1][0]) // 2)
ans[stack[-1][2]] = t
ans[odd[-1][2]] = t
elif stack[-1][1]=="L" and odd[-1][1]=="R":
t = m-abs((stack[-1][0] - odd[-1][0]) // 2)
ans[stack[-1][2]] = t
ans[odd[-1][2]] = t
elif stack[-1][1]=="R" and odd[-1][1]=="R":
t=m-abs((stack[-1][0]+odd[-1][0])//2)
ans[stack[-1][2]] = t
ans[odd[-1][2]] = t
stack.pop()
while len(stack)>1:
t = m - abs((stack[-1][0] + stack[-2][0]) // 2)
ans[stack[-1][2]] = t
ans[stack[-2][2]] = t
stack.pop()
print(*ans)
``` | instruction | 0 | 88,670 | 3 | 177,340 |
No | output | 1 | 88,670 | 3 | 177,341 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m.
The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate.
Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.
Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.
For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The first line of each testcase contains two integers n and m (1 β€ n β€ 3 β
10^5; 2 β€ m β€ 10^8) β the number of robots and the coordinate of the right wall.
The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β the starting coordinates of the robots.
The third line of each testcase contains n space-separated characters 'L' or 'R' β the starting directions of the robots ('L' stands for left and 'R' stands for right).
All coordinates x_i in the testcase are distinct.
The sum of n over all testcases doesn't exceed 3 β
10^5.
Output
For each testcase print n integers β for the i-th robot output the time it explodes at if it does and -1 otherwise.
Example
Input
5
7 12
1 2 3 4 9 10 11
R R L L R R R
2 10
1 6
R R
2 10
1 3
L L
1 10
5
R
7 8
6 1 7 2 3 5 4
R L R L L L L
Output
1 1 1 1 2 -1 2
-1 -1
2 2
-1
-1 2 7 3 2 7 3
Note
Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase:
<image>
Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer.
After second 3 robot 6 just drive infinitely because there's no robot to collide with.
Submitted Solution:
```
from __future__ import print_function
from sys import stdin,stdout
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
from collections.abc import Sequence, MutableSequence
except ImportError:
from collections import Sequence, MutableSequence
from functools import wraps
from sys import hexversion
if hexversion < 0x03000000:
from itertools import imap as map # pylint: disable=redefined-builtin
from itertools import izip as zip # pylint: disable=redefined-builtin
try:
from thread import get_ident
except ImportError:
from dummy_thread import get_ident
else:
from functools import reduce
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
def recursive_repr(fillvalue='...'):
"Decorator to make a repr function return fillvalue for a recursive call."
# pylint: disable=missing-docstring
# Copied from reprlib in Python 3
# https://hg.python.org/cpython/file/3.6/Lib/reprlib.py
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
class SortedList(MutableSequence):
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
# pylint: disable=unused-argument
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError('inherit SortedKeyList for key argument')
@property
def key(self): # pylint: disable=useless-return
return None
def _reset(self, load):
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError('{0!r} not in list'.format(value))
def _delete(self, pos, idx):
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
# Increment pos to point in the index to len(self._lists[pos]).
pos += self._offset
# Iterate until reaching the root of the index tree at pos = 0.
while pos:
# Right-child nodes are at odd indices. At such indices
# account the total below the left child node.
if not pos & 1:
total += _index[pos - 1]
# Advance pos to the parent node.
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = range(start, stop, step)
# Delete items from greatest index to least so
# that the indices remain valid throughout iteration.
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
# Whole slice optimization: start to stop slices the whole
# sorted list.
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
start_list = _lists[start_pos]
stop_idx = start_idx + stop - start
# Small slice optimization: start index and stop index are
# within the start list.
if len(start_list) >= stop_idx:
return start_list[start_idx:stop_idx]
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
# Return a list because a negative step could
# reverse the order of the items and this could
# be the desired behavior.
indices = range(start, stop, step)
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
raise NotImplementedError(message)
def __iter__(self):
return chain.from_iterable(self._lists)
def __reversed__(self):
return chain.from_iterable(map(reversed, reversed(self._lists)))
def reverse(self):
raise NotImplementedError('use ``reversed(sl)`` instead')
def islice(self, start=None, stop=None, reverse=False):
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(range(min_idx, max_idx))
return map(_lists[min_pos].__getitem__, indices)
indices = range(min_idx, max_idx)
return map(_lists[min_pos].__getitem__, indices)
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
map(_lists[max_pos].__getitem__, max_indices),
)
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, reversed(sublist_indices))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
chain.from_iterable(map(reversed, sublists)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, sublist_indices)
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
chain.from_iterable(sublists),
map(_lists[max_pos].__getitem__, max_indices),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
"""Return the size of the sorted list.
``sl.__len__()`` <==> ``len(sl)``
:return: size of sorted list
"""
return self._len
def bisect_left(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
return self.__class__(self)
__copy__ = copy
def append(self, value):
raise NotImplementedError('use ``sl.add(value)`` instead')
def extend(self, values):
raise NotImplementedError('use ``sl.update(values)`` instead')
def insert(self, index, value):
raise NotImplementedError('use ``sl.add(value)`` instead')
def pop(self, index=-1):
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
self._update(other)
return self
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted list and sequence."
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = '__{0}__'.format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'less than')
__gt__ = __make_cmp(gt, '>', 'greater than')
__le__ = __make_cmp(le, '<=', 'less than or equal to')
__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
__make_cmp = staticmethod(__make_cmp)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values,))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted list.
``sl.__repr__()`` <==> ``repr(sl)``
:return: string representation
"""
return '{0}({1!r})'.format(type(self).__name__, list(self))
def _check(self):
"""Check invariants of sorted list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
raise
def identity(value):
"Identity function."
return value
class SortedKeyList(SortedList):
def __init__(self, iterable=None, key=identity):
self._key = key
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
return self._key
def clear(self):
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, value):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(value)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, value)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([value])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > (self._load << 1):
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == value:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} not in list'.format(value))
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > (self._load >> 1):
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
min_key = self._key(minimum) if minimum is not None else None
max_key = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=min_key, max_key=max_key,
inclusive=inclusive, reverse=reverse,
)
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, value):
return self._bisect_key_left(self._key(value))
def bisect_right(self, value):
return self._bisect_key_right(self._key(value))
bisect = bisect_right
def bisect_key_left(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == value:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
return self.__class__(self, key=self._key)
__copy__ = copy
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(value))
if _lists[pos][idx] == value:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values, key=self._key)
__radd__ = __add__
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values, key=self._key)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values, self.key))
@recursive_repr()
def __repr__(self):
type_name = type(self).__name__
return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key)
def _check(self):
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert self._len == sum(len(sublist) for sublist in self._lists)
for sublist in self._keys:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
for val_sublist, key_sublist in zip(self._lists, self._keys):
assert len(val_sublist) == len(key_sublist)
for val, key in zip(val_sublist, key_sublist):
assert self._key(val) == key
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._keys[pos][-1]
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
def comp(M,l,r):
while len(r):
pos=l.bisect_left(r[0])
if pos==len(l):
break
val=(l[pos]-r[0])/2
ans[m[l[pos]]]=val
ans[m[r[0]]]=val
l.pop(pos)
r.pop(0)
while len(l)>1:
x1=l.pop(0)
x2=l.pop(0)
val=(x1+x2)/2
ans[m[x1]]=val
ans[m[x2]]=val
while len(r)>1:
x1=r.pop(0)
x2=r.pop(0)
val=(M-x1+M-x2)/2
ans[m[x1]]=val
ans[m[x2]]=val
if len(l)==1 and len(r)==1:
x1=l.pop()
x2=r.pop()
val=(M+M-x2+x1)/2
ans[m[x1]]=val
ans[m[x2]]=val
for _ in range(input()):
n,M=[int(i) for i in raw_input().split()]
a=[int(i) for i in raw_input().split()]
s=[i for i in raw_input().split()]
al=SortedList()
bl=SortedList()
ar=SortedList()
br=SortedList()
m={}
ans=[-1 for i in range(n)]
for i in range(n):
m[a[i]]=i
if a[i]%2==0:
if s[i]=='L':
al.add(a[i])
else:
ar.add(a[i])
else:
if s[i]=='L':
bl.add(a[i])
else:
br.add(a[i])
comp(M,al,ar)
comp(M,bl,br)
for i in ans:
print(i,end=" ")
print()
``` | instruction | 0 | 88,671 | 3 | 177,342 |
No | output | 1 | 88,671 | 3 | 177,343 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m.
The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate.
Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.
Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.
For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The first line of each testcase contains two integers n and m (1 β€ n β€ 3 β
10^5; 2 β€ m β€ 10^8) β the number of robots and the coordinate of the right wall.
The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β the starting coordinates of the robots.
The third line of each testcase contains n space-separated characters 'L' or 'R' β the starting directions of the robots ('L' stands for left and 'R' stands for right).
All coordinates x_i in the testcase are distinct.
The sum of n over all testcases doesn't exceed 3 β
10^5.
Output
For each testcase print n integers β for the i-th robot output the time it explodes at if it does and -1 otherwise.
Example
Input
5
7 12
1 2 3 4 9 10 11
R R L L R R R
2 10
1 6
R R
2 10
1 3
L L
1 10
5
R
7 8
6 1 7 2 3 5 4
R L R L L L L
Output
1 1 1 1 2 -1 2
-1 -1
2 2
-1
-1 2 7 3 2 7 3
Note
Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase:
<image>
Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer.
After second 3 robot 6 just drive infinitely because there's no robot to collide with.
Submitted Solution:
```
from __future__ import print_function
from sys import stdin,stdout
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
from collections.abc import Sequence, MutableSequence
except ImportError:
from collections import Sequence, MutableSequence
from functools import wraps
from sys import hexversion
if hexversion < 0x03000000:
from itertools import imap as map # pylint: disable=redefined-builtin
from itertools import izip as zip # pylint: disable=redefined-builtin
try:
from thread import get_ident
except ImportError:
from dummy_thread import get_ident
else:
from functools import reduce
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
def recursive_repr(fillvalue='...'):
"Decorator to make a repr function return fillvalue for a recursive call."
# pylint: disable=missing-docstring
# Copied from reprlib in Python 3
# https://hg.python.org/cpython/file/3.6/Lib/reprlib.py
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
class SortedList(MutableSequence):
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
# pylint: disable=unused-argument
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError('inherit SortedKeyList for key argument')
@property
def key(self): # pylint: disable=useless-return
return None
def _reset(self, load):
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError('{0!r} not in list'.format(value))
def _delete(self, pos, idx):
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
# Increment pos to point in the index to len(self._lists[pos]).
pos += self._offset
# Iterate until reaching the root of the index tree at pos = 0.
while pos:
# Right-child nodes are at odd indices. At such indices
# account the total below the left child node.
if not pos & 1:
total += _index[pos - 1]
# Advance pos to the parent node.
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = range(start, stop, step)
# Delete items from greatest index to least so
# that the indices remain valid throughout iteration.
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
# Whole slice optimization: start to stop slices the whole
# sorted list.
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
start_list = _lists[start_pos]
stop_idx = start_idx + stop - start
# Small slice optimization: start index and stop index are
# within the start list.
if len(start_list) >= stop_idx:
return start_list[start_idx:stop_idx]
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
# Return a list because a negative step could
# reverse the order of the items and this could
# be the desired behavior.
indices = range(start, stop, step)
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
raise NotImplementedError(message)
def __iter__(self):
return chain.from_iterable(self._lists)
def __reversed__(self):
return chain.from_iterable(map(reversed, reversed(self._lists)))
def reverse(self):
raise NotImplementedError('use ``reversed(sl)`` instead')
def islice(self, start=None, stop=None, reverse=False):
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(range(min_idx, max_idx))
return map(_lists[min_pos].__getitem__, indices)
indices = range(min_idx, max_idx)
return map(_lists[min_pos].__getitem__, indices)
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
map(_lists[max_pos].__getitem__, max_indices),
)
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, reversed(sublist_indices))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
chain.from_iterable(map(reversed, sublists)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, sublist_indices)
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
chain.from_iterable(sublists),
map(_lists[max_pos].__getitem__, max_indices),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
"""Return the size of the sorted list.
``sl.__len__()`` <==> ``len(sl)``
:return: size of sorted list
"""
return self._len
def bisect_left(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
return self.__class__(self)
__copy__ = copy
def append(self, value):
raise NotImplementedError('use ``sl.add(value)`` instead')
def extend(self, values):
raise NotImplementedError('use ``sl.update(values)`` instead')
def insert(self, index, value):
raise NotImplementedError('use ``sl.add(value)`` instead')
def pop(self, index=-1):
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
self._update(other)
return self
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted list and sequence."
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = '__{0}__'.format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'less than')
__gt__ = __make_cmp(gt, '>', 'greater than')
__le__ = __make_cmp(le, '<=', 'less than or equal to')
__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
__make_cmp = staticmethod(__make_cmp)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values,))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted list.
``sl.__repr__()`` <==> ``repr(sl)``
:return: string representation
"""
return '{0}({1!r})'.format(type(self).__name__, list(self))
def _check(self):
"""Check invariants of sorted list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
raise
def identity(value):
"Identity function."
return value
class SortedKeyList(SortedList):
def __init__(self, iterable=None, key=identity):
self._key = key
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
return self._key
def clear(self):
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, value):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(value)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, value)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([value])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > (self._load << 1):
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == value:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} not in list'.format(value))
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > (self._load >> 1):
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
min_key = self._key(minimum) if minimum is not None else None
max_key = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=min_key, max_key=max_key,
inclusive=inclusive, reverse=reverse,
)
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, value):
return self._bisect_key_left(self._key(value))
def bisect_right(self, value):
return self._bisect_key_right(self._key(value))
bisect = bisect_right
def bisect_key_left(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == value:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
return self.__class__(self, key=self._key)
__copy__ = copy
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(value))
if _lists[pos][idx] == value:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values, key=self._key)
__radd__ = __add__
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values, key=self._key)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values, self.key))
@recursive_repr()
def __repr__(self):
type_name = type(self).__name__
return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key)
def _check(self):
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert self._len == sum(len(sublist) for sublist in self._lists)
for sublist in self._keys:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
for val_sublist, key_sublist in zip(self._lists, self._keys):
assert len(val_sublist) == len(key_sublist)
for val, key in zip(val_sublist, key_sublist):
assert self._key(val) == key
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._keys[pos][-1]
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
def comp(M,l,r):
nr=[]
nl=[]
while len(r):
x=r.pop()
val=-1
while len(l)>0 and l[-1]>x:
if val!=-1:
nl.append(val)
val=l[-1]
l.pop()
if val==-1:
nr.append(x)
continue
y=val
val=(y-x)/2
ans[m[y]]=val
ans[m[x]]=val
while len(l):
nl.append(l.pop())
l=nl[:]
r=nr[:]
l.sort()
r.sort()
l=l[::-1]
while len(l)>1:
x1=l.pop()
x2=l.pop()
val=(x1+x2)/2
ans[m[x1]]=val
ans[m[x2]]=val
while len(r)>1:
x1=r.pop()
x2=r.pop()
val=(M-x1+M-x2)/2
ans[m[x1]]=val
ans[m[x2]]=val
if len(l)==1 and len(r)==1:
x1=l.pop()
x3=r.pop()
x2=M-x3
common=max(x1,x2)
pos1=common-x1
pos2=M-(common-x2)
tot=common+(pos2-pos1)/2
ans[m[x1]]=tot
ans[m[x3]]=tot
for _ in range(input()):
n,M=[int(i) for i in raw_input().split()]
a=[int(i) for i in raw_input().split()]
s=[i for i in raw_input().split()]
al=[]
bl=[]
ar=[]
br=[]
m={}
ans=[-1 for i in range(n)]
for i in range(n):
m[a[i]]=i
if a[i]%2==0:
if s[i]=='L':
al.append(a[i])
else:
ar.append(a[i])
else:
if s[i]=='L':
bl.append(a[i])
else:
br.append(a[i])
comp(M,al,ar)
comp(M,bl,br)
for i in ans:
print(i,end=" ")
print()
``` | instruction | 0 | 88,672 | 3 | 177,344 |
No | output | 1 | 88,672 | 3 | 177,345 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m.
The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate.
Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.
Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.
For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The first line of each testcase contains two integers n and m (1 β€ n β€ 3 β
10^5; 2 β€ m β€ 10^8) β the number of robots and the coordinate of the right wall.
The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β the starting coordinates of the robots.
The third line of each testcase contains n space-separated characters 'L' or 'R' β the starting directions of the robots ('L' stands for left and 'R' stands for right).
All coordinates x_i in the testcase are distinct.
The sum of n over all testcases doesn't exceed 3 β
10^5.
Output
For each testcase print n integers β for the i-th robot output the time it explodes at if it does and -1 otherwise.
Example
Input
5
7 12
1 2 3 4 9 10 11
R R L L R R R
2 10
1 6
R R
2 10
1 3
L L
1 10
5
R
7 8
6 1 7 2 3 5 4
R L R L L L L
Output
1 1 1 1 2 -1 2
-1 -1
2 2
-1
-1 2 7 3 2 7 3
Note
Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase:
<image>
Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer.
After second 3 robot 6 just drive infinitely because there's no robot to collide with.
Submitted Solution:
```
from __future__ import print_function
from sys import stdin,stdout
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
from collections.abc import Sequence, MutableSequence
except ImportError:
from collections import Sequence, MutableSequence
from functools import wraps
from sys import hexversion
if hexversion < 0x03000000:
from itertools import imap as map # pylint: disable=redefined-builtin
from itertools import izip as zip # pylint: disable=redefined-builtin
try:
from thread import get_ident
except ImportError:
from dummy_thread import get_ident
else:
from functools import reduce
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
def recursive_repr(fillvalue='...'):
"Decorator to make a repr function return fillvalue for a recursive call."
# pylint: disable=missing-docstring
# Copied from reprlib in Python 3
# https://hg.python.org/cpython/file/3.6/Lib/reprlib.py
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
class SortedList(MutableSequence):
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
# pylint: disable=unused-argument
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError('inherit SortedKeyList for key argument')
@property
def key(self): # pylint: disable=useless-return
return None
def _reset(self, load):
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError('{0!r} not in list'.format(value))
def _delete(self, pos, idx):
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
# Increment pos to point in the index to len(self._lists[pos]).
pos += self._offset
# Iterate until reaching the root of the index tree at pos = 0.
while pos:
# Right-child nodes are at odd indices. At such indices
# account the total below the left child node.
if not pos & 1:
total += _index[pos - 1]
# Advance pos to the parent node.
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = range(start, stop, step)
# Delete items from greatest index to least so
# that the indices remain valid throughout iteration.
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
# Whole slice optimization: start to stop slices the whole
# sorted list.
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
start_list = _lists[start_pos]
stop_idx = start_idx + stop - start
# Small slice optimization: start index and stop index are
# within the start list.
if len(start_list) >= stop_idx:
return start_list[start_idx:stop_idx]
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
# Return a list because a negative step could
# reverse the order of the items and this could
# be the desired behavior.
indices = range(start, stop, step)
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
raise NotImplementedError(message)
def __iter__(self):
return chain.from_iterable(self._lists)
def __reversed__(self):
return chain.from_iterable(map(reversed, reversed(self._lists)))
def reverse(self):
raise NotImplementedError('use ``reversed(sl)`` instead')
def islice(self, start=None, stop=None, reverse=False):
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(range(min_idx, max_idx))
return map(_lists[min_pos].__getitem__, indices)
indices = range(min_idx, max_idx)
return map(_lists[min_pos].__getitem__, indices)
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
map(_lists[max_pos].__getitem__, max_indices),
)
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, reversed(sublist_indices))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
chain.from_iterable(map(reversed, sublists)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, sublist_indices)
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
chain.from_iterable(sublists),
map(_lists[max_pos].__getitem__, max_indices),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
"""Return the size of the sorted list.
``sl.__len__()`` <==> ``len(sl)``
:return: size of sorted list
"""
return self._len
def bisect_left(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
return self.__class__(self)
__copy__ = copy
def append(self, value):
raise NotImplementedError('use ``sl.add(value)`` instead')
def extend(self, values):
raise NotImplementedError('use ``sl.update(values)`` instead')
def insert(self, index, value):
raise NotImplementedError('use ``sl.add(value)`` instead')
def pop(self, index=-1):
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
self._update(other)
return self
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted list and sequence."
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = '__{0}__'.format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'less than')
__gt__ = __make_cmp(gt, '>', 'greater than')
__le__ = __make_cmp(le, '<=', 'less than or equal to')
__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
__make_cmp = staticmethod(__make_cmp)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values,))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted list.
``sl.__repr__()`` <==> ``repr(sl)``
:return: string representation
"""
return '{0}({1!r})'.format(type(self).__name__, list(self))
def _check(self):
"""Check invariants of sorted list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
raise
def identity(value):
"Identity function."
return value
class SortedKeyList(SortedList):
def __init__(self, iterable=None, key=identity):
self._key = key
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
return self._key
def clear(self):
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, value):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(value)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, value)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([value])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > (self._load << 1):
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == value:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} not in list'.format(value))
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > (self._load >> 1):
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
min_key = self._key(minimum) if minimum is not None else None
max_key = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=min_key, max_key=max_key,
inclusive=inclusive, reverse=reverse,
)
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, value):
return self._bisect_key_left(self._key(value))
def bisect_right(self, value):
return self._bisect_key_right(self._key(value))
bisect = bisect_right
def bisect_key_left(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == value:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
return self.__class__(self, key=self._key)
__copy__ = copy
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(value))
if _lists[pos][idx] == value:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values, key=self._key)
__radd__ = __add__
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values, key=self._key)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values, self.key))
@recursive_repr()
def __repr__(self):
type_name = type(self).__name__
return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key)
def _check(self):
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert self._len == sum(len(sublist) for sublist in self._lists)
for sublist in self._keys:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
for val_sublist, key_sublist in zip(self._lists, self._keys):
assert len(val_sublist) == len(key_sublist)
for val, key in zip(val_sublist, key_sublist):
assert self._key(val) == key
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._keys[pos][-1]
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
def comp(M,l,r):
nr=[]
nl=[]
krr=SortedList()
for i in l:
krr.add(i)
while len(r):
x=r.pop()
pos=krr.bisect_left(x)
if pos==len(krr):
nr.append(x)
continue
y=krr[pos]
val=(y-x)/2
ans[m[y]]=val
ans[m[x]]=val
krr.pop(pos)
l=[]
while len(krr):
l.append(krr.pop())
r=nr[:]
l.sort()
r.sort()
l=l[::-1]
while len(l)>1:
x1=l.pop()
x2=l.pop()
val=(x1+x2)/2
ans[m[x1]]=val
ans[m[x2]]=val
while len(r)>1:
x1=r.pop()
x2=r.pop()
val=(M-x1+M-x2)/2
ans[m[x1]]=val
ans[m[x2]]=val
if len(l)==1 and len(r)==1:
x1=l.pop()
x3=r.pop()
x2=M-x3
common=max(x1,x2)
pos1=common-x1
pos2=M-(common-x2)
tot=common+(pos2-pos1)/2
ans[m[x1]]=tot
ans[m[x3]]=tot
for _ in range(input()):
n,M=[int(i) for i in raw_input().split()]
a=[int(i) for i in raw_input().split()]
s=[i for i in raw_input().split()]
al=[]
bl=[]
ar=[]
br=[]
m={}
ans=[-1 for i in range(n)]
for i in range(n):
m[a[i]]=i
if a[i]%2==0:
if s[i]=='L':
al.append(a[i])
else:
ar.append(a[i])
else:
if s[i]=='L':
bl.append(a[i])
else:
br.append(a[i])
comp(M,al,ar)
comp(M,bl,br)
for i in ans:
print(i,end=" ")
print()
``` | instruction | 0 | 88,673 | 3 | 177,346 |
No | output | 1 | 88,673 | 3 | 177,347 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m.
The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate.
Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.
Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.
For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then the descriptions of t testcases follow.
The first line of each testcase contains two integers n and m (1 β€ n β€ 3 β
10^5; 2 β€ m β€ 10^8) β the number of robots and the coordinate of the right wall.
The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β the starting coordinates of the robots.
The third line of each testcase contains n space-separated characters 'L' or 'R' β the starting directions of the robots ('L' stands for left and 'R' stands for right).
All coordinates x_i in the testcase are distinct.
The sum of n over all testcases doesn't exceed 3 β
10^5.
Output
For each testcase print n integers β for the i-th robot output the time it explodes at if it does and -1 otherwise.
Example
Input
5
7 12
1 2 3 4 9 10 11
R R L L R R R
2 10
1 6
R R
2 10
1 3
L L
1 10
5
R
7 8
6 1 7 2 3 5 4
R L R L L L L
Output
1 1 1 1 2 -1 2
-1 -1
2 2
-1
-1 2 7 3 2 7 3
Note
Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase:
<image>
Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer.
After second 3 robot 6 just drive infinitely because there's no robot to collide with.
Submitted Solution:
```
from __future__ import print_function
from sys import stdin,stdout
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
from collections.abc import Sequence, MutableSequence
except ImportError:
from collections import Sequence, MutableSequence
from functools import wraps
from sys import hexversion
if hexversion < 0x03000000:
from itertools import imap as map # pylint: disable=redefined-builtin
from itertools import izip as zip # pylint: disable=redefined-builtin
try:
from thread import get_ident
except ImportError:
from dummy_thread import get_ident
else:
from functools import reduce
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
def recursive_repr(fillvalue='...'):
"Decorator to make a repr function return fillvalue for a recursive call."
# pylint: disable=missing-docstring
# Copied from reprlib in Python 3
# https://hg.python.org/cpython/file/3.6/Lib/reprlib.py
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
class SortedList(MutableSequence):
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
# pylint: disable=unused-argument
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError('inherit SortedKeyList for key argument')
@property
def key(self): # pylint: disable=useless-return
return None
def _reset(self, load):
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError('{0!r} not in list'.format(value))
def _delete(self, pos, idx):
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
# Increment pos to point in the index to len(self._lists[pos]).
pos += self._offset
# Iterate until reaching the root of the index tree at pos = 0.
while pos:
# Right-child nodes are at odd indices. At such indices
# account the total below the left child node.
if not pos & 1:
total += _index[pos - 1]
# Advance pos to the parent node.
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = range(start, stop, step)
# Delete items from greatest index to least so
# that the indices remain valid throughout iteration.
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
# Whole slice optimization: start to stop slices the whole
# sorted list.
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
start_list = _lists[start_pos]
stop_idx = start_idx + stop - start
# Small slice optimization: start index and stop index are
# within the start list.
if len(start_list) >= stop_idx:
return start_list[start_idx:stop_idx]
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
# Return a list because a negative step could
# reverse the order of the items and this could
# be the desired behavior.
indices = range(start, stop, step)
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
raise NotImplementedError(message)
def __iter__(self):
return chain.from_iterable(self._lists)
def __reversed__(self):
return chain.from_iterable(map(reversed, reversed(self._lists)))
def reverse(self):
raise NotImplementedError('use ``reversed(sl)`` instead')
def islice(self, start=None, stop=None, reverse=False):
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(range(min_idx, max_idx))
return map(_lists[min_pos].__getitem__, indices)
indices = range(min_idx, max_idx)
return map(_lists[min_pos].__getitem__, indices)
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
map(_lists[max_pos].__getitem__, max_indices),
)
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, reversed(sublist_indices))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
chain.from_iterable(map(reversed, sublists)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, sublist_indices)
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
chain.from_iterable(sublists),
map(_lists[max_pos].__getitem__, max_indices),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
"""Return the size of the sorted list.
``sl.__len__()`` <==> ``len(sl)``
:return: size of sorted list
"""
return self._len
def bisect_left(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
return self.__class__(self)
__copy__ = copy
def append(self, value):
raise NotImplementedError('use ``sl.add(value)`` instead')
def extend(self, values):
raise NotImplementedError('use ``sl.update(values)`` instead')
def insert(self, index, value):
raise NotImplementedError('use ``sl.add(value)`` instead')
def pop(self, index=-1):
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
self._update(other)
return self
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted list and sequence."
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = '__{0}__'.format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'less than')
__gt__ = __make_cmp(gt, '>', 'greater than')
__le__ = __make_cmp(le, '<=', 'less than or equal to')
__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
__make_cmp = staticmethod(__make_cmp)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values,))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted list.
``sl.__repr__()`` <==> ``repr(sl)``
:return: string representation
"""
return '{0}({1!r})'.format(type(self).__name__, list(self))
def _check(self):
"""Check invariants of sorted list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
raise
def identity(value):
"Identity function."
return value
class SortedKeyList(SortedList):
def __init__(self, iterable=None, key=identity):
self._key = key
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
return self._key
def clear(self):
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, value):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(value)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, value)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([value])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > (self._load << 1):
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == value:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} not in list'.format(value))
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > (self._load >> 1):
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
min_key = self._key(minimum) if minimum is not None else None
max_key = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=min_key, max_key=max_key,
inclusive=inclusive, reverse=reverse,
)
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, value):
return self._bisect_key_left(self._key(value))
def bisect_right(self, value):
return self._bisect_key_right(self._key(value))
bisect = bisect_right
def bisect_key_left(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == value:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
return self.__class__(self, key=self._key)
__copy__ = copy
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(value))
if _lists[pos][idx] == value:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values, key=self._key)
__radd__ = __add__
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values, key=self._key)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values, self.key))
@recursive_repr()
def __repr__(self):
type_name = type(self).__name__
return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key)
def _check(self):
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert self._len == sum(len(sublist) for sublist in self._lists)
for sublist in self._keys:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
for val_sublist, key_sublist in zip(self._lists, self._keys):
assert len(val_sublist) == len(key_sublist)
for val, key in zip(val_sublist, key_sublist):
assert self._key(val) == key
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._keys[pos][-1]
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
def comp(M,l,r):
while len(r):
pos=l.bisect_left(r[0])
if pos==len(l):
break
val=(l[pos]-r[0])/2
ans[m[l[pos]]]=val
ans[m[r[0]]]=val
l.pop(pos)
r.pop(0)
while len(l)>1:
x1=l.pop(0)
x2=l.pop(0)
val=(x1+x2)/2
ans[m[x1]]=val
ans[m[x2]]=val
while len(r)>1:
x1=r.pop()
x2=r.pop()
val=(M-x1+M-x2)/2
ans[m[x1]]=val
ans[m[x2]]=val
if len(l)==1 and len(r)==1:
x1=l.pop()
x2=r.pop()
val=(M+M-x2+x1)/2
ans[m[x1]]=val
ans[m[x2]]=val
for _ in range(input()):
n,M=[int(i) for i in raw_input().split()]
a=[int(i) for i in raw_input().split()]
s=[i for i in raw_input().split()]
al=SortedList()
bl=SortedList()
ar=SortedList()
br=SortedList()
m={}
ans=[-1 for i in range(n)]
for i in range(n):
m[a[i]]=i
if a[i]%2==0:
if s[i]=='L':
al.add(a[i])
else:
ar.add(a[i])
else:
if s[i]=='L':
bl.add(a[i])
else:
br.add(a[i])
comp(M,al,ar)
comp(M,bl,br)
for i in ans:
print(i,end=" ")
print()
``` | instruction | 0 | 88,674 | 3 | 177,348 |
No | output | 1 | 88,674 | 3 | 177,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | instruction | 0 | 88,734 | 3 | 177,468 |
Tags: math, number theory
Correct Solution:
```
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ######### #
###### ######### # # # # # # ######### #
# # # # # # # # # # #### # # #
# # # # # # # ## # # # # #
###### # # ####### ####### # # ##### # # # #
from __future__ import print_function # for PyPy2
# from itertools import permutations as perm
# from functools import cmp_to_key # for adding custom comparator
# from fractions import Fraction
# from collections import *
from sys import stdin
# from bisect import *
# from heapq import *
# from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")
a, b = gil()
ans = 0
while min(a, b) != 1:
n, d = max(a, b), min(a, b)
ans += n//d
a, b = n%d, d
ans += max(a, b)
print(ans)
``` | output | 1 | 88,734 | 3 | 177,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | instruction | 0 | 88,735 | 3 | 177,470 |
Tags: math, number theory
Correct Solution:
```
def sol(a,b):
global ans
ans+=a//b
a=a%b
if a==0:
return 0
return sol(b,a)
ans=0
a,b=map(int,input().split())
sol(max(a,b),min(a,b))
print(ans)
``` | output | 1 | 88,735 | 3 | 177,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | instruction | 0 | 88,736 | 3 | 177,472 |
Tags: math, number theory
Correct Solution:
```
a=[0]+[int(i)for i in input().split()]
while a[1]*a[2]!=0:
a=[a[0]+a[1]//a[2],a[2],a[1]%a[2]]
print(a[0])
``` | output | 1 | 88,736 | 3 | 177,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | instruction | 0 | 88,737 | 3 | 177,474 |
Tags: math, number theory
Correct Solution:
```
a,b=map(int,input().split())
ans=0
while a and b:
ans+=a//b
a,b=b,a%b
print(ans)
``` | output | 1 | 88,737 | 3 | 177,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | instruction | 0 | 88,738 | 3 | 177,476 |
Tags: math, number theory
Correct Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import math
import os
import sys
from fractions import *
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import *
from collections import *
# sys.setrecursionlimit(10**5)
M = 10 ** 9 + 7
# print(math.factorial(5))
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
# sys.setrecursionlimit(10**6)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def inpu(): return int(inp())
# -----------------------------------------------------------------
def regularbracket(t):
p = 0
for i in t:
if i == "(":
p += 1
else:
p -= 1
if p < 0:
return False
else:
if p > 0:
return False
else:
return True
# -------------------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <= key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# ------------------------------reverse string(pallindrome)
def reverse1(string):
pp = ""
for i in string[::-1]:
pp += i
if pp == string:
return True
return False
# --------------------------------reverse list(paindrome)
def reverse2(list1):
l = []
for i in list1[::-1]:
l.append(i)
if l == list1:
return True
return False
def mex(list1):
# list1 = sorted(list1)
p = max(list1) + 1
for i in range(len(list1)):
if list1[i] != i:
p = i
break
return p
def sumofdigits(n):
n = str(n)
s1 = 0
for i in n:
s1 += int(i)
return s1
def perfect_square(n):
s = math.sqrt(n)
if s == int(s):
return True
return False
# -----------------------------roman
def roman_number(x):
if x > 15999:
return
value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
symbol = ["F", "MF", "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
roman = ""
i = 0
while x > 0:
div = x // value[i]
x = x % value[i]
while div:
roman += symbol[i]
div -= 1
i += 1
return roman
def soretd(s):
for i in range(1, len(s)):
if s[i - 1] > s[i]:
return False
return True
# print(soretd("1"))
# ---------------------------
def countRhombi(h, w):
ct = 0
for i in range(2, h + 1, 2):
for j in range(2, w + 1, 2):
ct += (h - i + 1) * (w - j + 1)
return ct
def countrhombi2(h, w):
return ((h * h) // 4) * ((w * w) // 4)
# ---------------------------------
def binpow(a, b):
if b == 0:
return 1
else:
res = binpow(a, b // 2)
if b % 2 != 0:
return res * res * a
else:
return res * res
# -------------------------------------------------------
def binpowmodulus(a, b, m):
a %= m
res = 1
while (b > 0):
if (b & 1):
res = res * a % m
a = a * a % m
b >>= 1
return res
# -------------------------------------------------------------
def coprime_to_n(n):
result = n
i = 2
while (i * i <= n):
if (n % i == 0):
while (n % i == 0):
n //= i
result -= result // i
i += 1
if (n > 1):
result -= result // n
return result
# -------------------prime
def prime(x):
if x == 1:
return False
else:
for i in range(2, int(math.sqrt(x)) + 1):
# print(x)
if (x % i == 0):
return False
else:
return True
def luckynumwithequalnumberoffourandseven(x, n, a):
if x >= n and str(x).count("4") == str(x).count("7"):
a.append(x)
else:
if x < 1e12:
luckynumwithequalnumberoffourandseven(x * 10 + 4, n, a)
luckynumwithequalnumberoffourandseven(x * 10 + 7, n, a)
return a
def luckynuber(x, n, a):
p = set(str(x))
if len(p) <= 2:
a.append(x)
if x < n:
luckynuber(x + 1, n, a)
return a
# ------------------------------------------------------interactive problems
def interact(type, x):
if type == "r":
inp = input()
return inp.strip()
else:
print(x, flush=True)
# ------------------------------------------------------------------zero at end of factorial of a number
def findTrailingZeros(n):
# Initialize result
count = 0
# Keep dividing n by
# 5 & update Count
while (n >= 5):
n //= 5
count += n
return count
# -----------------------------------------------merge sort
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr) // 2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# -----------------------------------------------lucky number with two lucky any digits
res = set()
def solven(p, l, a, b, n): # given number
if p > n or l > 10:
return
if p > 0:
res.add(p)
solven(p * 10 + a, l + 1, a, b, n)
solven(p * 10 + b, l + 1, a, b, n)
# problem
"""
n = int(input())
for a in range(0, 10):
for b in range(0, a):
solve(0, 0)
print(len(res))
"""
# Python3 program to find all subsets
# by backtracking.
# In the array A at every step we have two
# choices for each element either we can
# ignore the element or we can include the
# element in our subset
def subsetsUtil(A, subset, index, d):
print(*subset)
s = sum(subset)
d.append(s)
for i in range(index, len(A)):
# include the A[i] in subset.
subset.append(A[i])
# move onto the next element.
subsetsUtil(A, subset, i + 1, d)
# exclude the A[i] from subset and
# triggers backtracking.
subset.pop(-1)
return d
def subsetSums(arr, l, r, d, sum=0):
if l > r:
d.append(sum)
return
subsetSums(arr, l + 1, r, d, sum + arr[l])
# Subset excluding arr[l]
subsetSums(arr, l + 1, r, d, sum)
return d
def print_factors(x):
factors = []
for i in range(1, x + 1):
if x % i == 0:
factors.append(i)
return (factors)
# -----------------------------------------------
def calc(X, d, ans, D):
# print(X,d)
if len(X) == 0:
return
i = X.index(max(X))
ans[D[max(X)]] = d
Y = X[:i]
Z = X[i + 1:]
calc(Y, d + 1, ans, D)
calc(Z, d + 1, ans, D)
# ---------------------------------------
def factorization(n, l):
c = n
if prime(n) == True:
l.append(n)
return l
for i in range(2, c):
if n == 1:
break
while n % i == 0:
l.append(i)
n = n // i
return l
# endregion------------------------------
def good(b):
l = []
i = 0
while (len(b) != 0):
if b[i] < b[len(b) - 1 - i]:
l.append(b[i])
b.remove(b[i])
else:
l.append(b[len(b) - 1 - i])
b.remove(b[len(b) - 1 - i])
if l == sorted(l):
# print(l)
return True
return False
# arr=[]
# print(good(arr))
def generate(st, s):
if len(s) == 0:
return
# If current string is not already present.
if s not in st:
st.add(s)
# Traverse current string, one by one
# remove every character and recur.
for i in range(len(s)):
t = list(s).copy()
t.remove(s[i])
t = ''.join(t)
generate(st, t)
return
#=--------------------------------------------longest increasing subsequence
def largestincreasingsubsequence(A):
l = [1]*len(A)
sub=[]
for i in range(1,len(l)):
for k in range(i):
if A[k]<A[i]:
sub.append(l[k])
l[i]=1+max(sub,default=0)
return max(l,default=0)
#----------------------------------longest palindromic substring
# Python3 program for the
# above approach
# Function to calculate
# Bitwise OR of sums of
# all subsequences
def findOR(nums, N):
# Stores the prefix
# sum of nums[]
prefix_sum = 0
# Stores the bitwise OR of
# sum of each subsequence
result = 0
# Iterate through array nums[]
for i in range(N):
# Bits set in nums[i] are
# also set in result
result |= nums[i]
# Calculate prefix_sum
prefix_sum += nums[i]
# Bits set in prefix_sum
# are also set in result
result |= prefix_sum
# Return the result
return result
#l=[]
def OR(a, n):
ans = a[0]
for i in range(1, n):
ans |= a[i]
#l.append(ans)
return ans
"""
def main():
n = inpu()
arr = lis()
l=[]
p=[]
q=[]
for i in range(len(arr)):
q.append([arr[i],i+1])
#print(q)
q.sort()
#print(q)
for i in range(0,n,2):
l.append(q[i][1])
for i in range(1,n,2):
p.append(q[i][1])
print(len(l))
print(*l)
print(len(p))
print(*p)
if __name__ == '__main__':
main()
"""
"""
def main():
n=inpu()
arr = lis()
a=0
b=sum(arr)
cnt=0
for i in range(len(arr)):
a+=arr[i]
b-=arr[i]
#print(a,b)
if a==b:
cnt+=1
if a!=0:
print(cnt)
else:
print(cnt-1)
if __name__ == '__main__':
main()
"""
"""
def main():
n = inpu()
arr = lis()
print(max(((sum(arr) - 1) // (n - 1)) + 1, max(arr)))
if __name__ == '__main__':
main()
"""
"""
def main():
n = int(input())
val = [0] * (n + 1)
add = [0] * (n + 1)
ptr = 1
sum = 0
res = [0] * n
for i in range(n):
l = lis()
if l[0] == 1:
a, x = l[1:]
add[a - 1] += x
sum += a * x
elif l[0] == 2:
k = l[1]
val[ptr] = k
sum += k
ptr += 1
else:
ptr -= 1
sum -= val[ptr]
sum -= add[ptr]
add[ptr - 1] += add[ptr]
add[ptr] = 0
res[i] = sum / ptr
print('\n'.join(str(x) for x in res))
if __name__ == '__main__':
main()
"""
"""
def main():
n,k=sep()
arr=lis()
arr = sorted(arr)
l = 0
s = 0
ans = 1
best = arr[0]
for i in range(1, n):
s += (i - l) * (arr[i] - arr[i - 1])
while s > k:
s -= arr[i] - arr[l]
l += 1
if i - l + 1 > ans:
ans = i - l + 1
best = arr[i]
print(ans, best)
if __name__ == '__main__':
main()
"""
def main():
a,b = sep()
cnt=0
while(b!=0):
cnt+=(a//b)
a,b = b,a%b
print(cnt)
if __name__ == '__main__':
main()
``` | output | 1 | 88,738 | 3 | 177,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | instruction | 0 | 88,739 | 3 | 177,478 |
Tags: math, number theory
Correct Solution:
```
import sys
import math
MAXNUM = math.inf
MINNUM = -1 * math.inf
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def solve(a, b):
counter = 1
while a != 1 and b != 1: # a num b denom
if a > b: # num greater than denom, so subtract by 1
diff = a // b
a -= b * diff
counter += diff
else: # denom > num
diff = b // a
b -= a * diff
counter += diff
if a > 1:
counter += a - 1
if b > 1:
counter += b - 1
return counter
def printOutput(ans):
sys.stdout.write(str(ans) + "\n") # add to me
def readinput():
a, b = getInts()
printOutput(solve(a, b))
readinput()
``` | output | 1 | 88,739 | 3 | 177,479 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | instruction | 0 | 88,740 | 3 | 177,480 |
Tags: math, number theory
Correct Solution:
```
def gcd(a,b):
if b==0: return 0
return a//b+gcd(b,a%b)
a,b=map(int,input().split())
print(gcd(a,b))
``` | output | 1 | 88,740 | 3 | 177,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | instruction | 0 | 88,741 | 3 | 177,482 |
Tags: math, number theory
Correct Solution:
```
import sys
import string
import math
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
from fractions import Fraction
def mi(s):
return map(int, s.strip().split())
def lmi(s):
return list(mi(s))
def tmi(s):
return tuple(mi(s))
def mf(f, s):
return map(f, s)
def lmf(f, s):
return list(mf(f, s))
def js(lst):
return " ".join(str(d) for d in lst)
def jsns(lst):
return "".join(str(d) for d in lst)
def line():
return sys.stdin.readline().strip()
def linesp():
return line().split()
def iline():
return int(line())
def mat(n):
matr = []
for _ in range(n):
matr.append(linesp())
return matr
def matns(n):
mat = []
for _ in range(n):
mat.append([c for c in line()])
return mat
def mati(n):
mat = []
for _ in range(n):
mat.append(lmi(line()))
return mat
def pmat(mat):
for row in mat:
print(js(row))
def recb(a,b):
# So, can we compute this in constant time.
if a==b:
return 1
elif a>b:
return 1+rec(a-b,b)
else:
return 1+rec(a,b-a)
def rec(a,b):
ans=0
while True:
if a==b:
ans+=1
break
elif a==0 or b==0:
break
if a>b:
k=(a-a%b)//b
a,b=a%b,b
elif a<b:
k=(b-b%a)//a
a,b=a,b%a
ans+=k
return ans
def main():
a,b=mi(line())
print(rec(a,b))
main()
``` | output | 1 | 88,741 | 3 | 177,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Submitted Solution:
```
a, b = map(int, input().split())
ans = 0
while a and b:
if a % b == 0 or b % a == 0:
print(max(a // b, b // a) + ans)
exit(0)
if a - b > 0:
ans += a // b
a, b = a % b, b
else:
ans += b // a
a, b = a, b % a
if a % b == 0:
ans += a // b
else:
ans += b // a
print(ans)
``` | instruction | 0 | 88,742 | 3 | 177,484 |
Yes | output | 1 | 88,742 | 3 | 177,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Submitted Solution:
```
from functools import reduce
from operator import *
from math import *
from sys import *
from string import *
setrecursionlimit(10**7)
RI=lambda: list(map(int,input().split()))
RS=lambda: input().rstrip().split()
#################################################
n,m=RI()
ans=0
while m:
ans+=n//m
n,m= m,n%m
print(ans)
``` | instruction | 0 | 88,743 | 3 | 177,486 |
Yes | output | 1 | 88,743 | 3 | 177,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Submitted Solution:
```
a, b = map(int, input().split())
def calc(a, b):
if a <= 0 or b <= 0:
return 0
if a == 1:
return b
if b == 1:
return a
if a >= b:
return a // b + calc(a % b, b)
return b // a + calc(a, b % a)
print(calc(a, b))
``` | instruction | 0 | 88,744 | 3 | 177,488 |
Yes | output | 1 | 88,744 | 3 | 177,489 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Submitted Solution:
```
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest
# sys.setrecursionlimit(111111)
INF=999999999999999999999999
alphabets="abcdefghijklmnopqrstuvwxyz"
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
class SegTree:
def __init__(self, n):
self.N = 1 << n.bit_length()
self.tree = [0] * (self.N<<1)
def update(self, i, j, v):
i += self.N
j += self.N
while i <= j:
if i%2==1: self.tree[i] += v
if j%2==0: self.tree[j] += v
i, j = (i+1) >> 1, (j-1) >> 1
def query(self, i):
v = 0
i += self.N
while i > 0:
v += self.tree[i]
i >>= 1
return v
def SieveOfEratosthenes(limit):
"""Returns all primes not greater than limit."""
isPrime = [True]*(limit+1)
isPrime[0] = isPrime[1] = False
primes = []
for i in range(2, limit+1):
if not isPrime[i]:continue
primes += [i]
for j in range(i*i, limit+1, i):
isPrime[j] = False
return primes
def main():
mod=1000000007
# InverseofNumber(mod)
# InverseofFactorial(mod)
# factorial(mod)
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
###CODE
tc = 1
for _ in range(tc):
a,b=ria()
# LOGIC-
# actually the quesn can easily understood as
# we have 1 ohm resistor
# we have 2 options now
# we can add 1 ohm resistor in series to this
# or we can add 1 ohm resistor in parallel to this
# let say we get to a/b ohm circuit system using k resistors
# now we add 1 resistor in series and parallel and see what happens
# a/b becomes (a+b)/b in series and a/(a+b) in parallel using k+1 resistors
# so if we have resistance as a/b it becomes (a+b)/b or a/(a+b) using 1 resistor
# in other words :
# so if we had resistance a/b it would have been
# (a-b)/a without 1 ohm resistor in series
# a/(b-a) without 1 ohm resistor in parallel
# func(a,b)=func(a-b,b) or func(a,b-a)
# does it ring a bell?
# Adding 1 ohm resistor to a circuit is just reverse of euclidean algo for finding gcd
# That means that the answer is equal to the number of steps in standard Euclidean algorithm.
# but basic gcd(a,b)=gcd(b-a,a) wont work we have to use mod to calculate faster
# like gcd(a,b)=gcd(b,a%b)
op=0
while min(a,b):
if a>b:
op+=a//b
a%=b
else:
op+=b//a
b%=a
wi(op)
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
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, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
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()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
``` | instruction | 0 | 88,745 | 3 | 177,490 |
Yes | output | 1 | 88,745 | 3 | 177,491 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Submitted Solution:
```
from math import gcd
def main():
a, b = map(int, input().split())
r = a // b
ans = r
a = a % b
if a > 0:
a, b = b, a
r = a // b
ans += r
a = a % b
ans += b * a
print(ans)
if __name__ == "__main__":
main()
``` | instruction | 0 | 88,746 | 3 | 177,492 |
No | output | 1 | 88,746 | 3 | 177,493 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Submitted Solution:
```
#https://codeforces.com/problemset/problem/343/A
inp = input()
a,b = int(inp.split()[0]) , int(inp.split()[1])
from math import floor
Sum=0
def work(a,b):
global Sum
if a/float(b) > 1:
Sum+= floor(a/float(b))
work(a-(b*floor(a/float(b))) , b)
elif a/float(b) < 1:
Sum+=b
else:
Sum+=1
work(a,b)
print(Sum)
``` | instruction | 0 | 88,747 | 3 | 177,494 |
No | output | 1 | 88,747 | 3 | 177,495 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Submitted Solution:
```
I = lambda : list(map(int, input().split(' ')))
a, b = I()
if a <= b:
print(b)
else:
print(a//b + a%b)
``` | instruction | 0 | 88,748 | 3 | 177,496 |
No | output | 1 | 88,748 | 3 | 177,497 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Submitted Solution:
```
from math import gcd
a, b = map(int, input().split(" "))
x = gcd(a,b)
a, b = a/x, b/x
ans = 0
ans += a//b
a -= a//b
print(int(ans))
``` | instruction | 0 | 88,749 | 3 | 177,498 |
No | output | 1 | 88,749 | 3 | 177,499 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2. | instruction | 0 | 88,833 | 3 | 177,666 |
Tags: brute force, implementation
Correct Solution:
```
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect, insort
from time import perf_counter
from fractions import Fraction
import copy
from copy import deepcopy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,6)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
def pmat(A):
for ele in A:
print(*ele,end="\n")
n=L()[0]
A=L()
B=[i for i in range(n)]
s=set()
ans="No"
while(tuple(A) not in s):
s.add(tuple(A))
z=1
for i in range(n):
A[i]=(A[i]+z)%n
z*=-1
if A==B:
ans="Yes"
print(ans)
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
``` | output | 1 | 88,833 | 3 | 177,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2. | instruction | 0 | 88,834 | 3 | 177,668 |
Tags: brute force, implementation
Correct Solution:
```
n = int(input())
l = [int(i) for i in input().split()]
d = (n - l[0]) % n
for i in range(1, n):
r = n
if i & 1 == 0:
if i >= l[i]:
r = i - l[i]
else:
r = i - l[i] + n
else:
if i <= l[i]:
r = l[i] - i
else:
r = l[i] - i + n
if r != d:
print("No")
d = -1
break
if d >= 0:
print("Yes")
``` | output | 1 | 88,834 | 3 | 177,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2. | instruction | 0 | 88,835 | 3 | 177,670 |
Tags: brute force, implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split(' ')))
count = n - a[0]
for i in range(n):
if i % 2 == 0:
a[i] = (a[i] + count + n) % n
else:
a[i] = (a[i] - count + n) % n
if a[i] != i:
print("No")
exit()
print("Yes")
``` | output | 1 | 88,835 | 3 | 177,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2. | instruction | 0 | 88,836 | 3 | 177,672 |
Tags: brute force, implementation
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
diff = (n - a[0]) % n
for i in range(1, n):
if i % 2 == 0:
if (a[i] + diff) % n != i:
#print((a[i] - diff) % n, i)
print("No")
exit()
else:
if (a[i] - diff) % n != i:
#print((a[i] - diff) % n, i)
print("No")
exit()
print("Yes")
``` | output | 1 | 88,836 | 3 | 177,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2. | instruction | 0 | 88,837 | 3 | 177,674 |
Tags: brute force, implementation
Correct Solution:
```
n, a, move = int(input()), list(map(int, input().split())), []
for i in range(n):
if i & 1:
move.append(((a[i] + 1) + (n - 1 - i)) % n)
else:
move.append((n - a[i] + i) % n)
print('Yes' if len(set(move)) == 1 else 'NO')
``` | output | 1 | 88,837 | 3 | 177,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2. | instruction | 0 | 88,838 | 3 | 177,676 |
Tags: brute force, implementation
Correct Solution:
```
from sys import stdout
n = int(input())
gears = list(map(int, input().split()))
targetGears = []
for i in range(0, n):
targetGears.append(i)
def check():
for i in range(0, n):
if(gears == targetGears):
stdout.write('Yes')
return
for j in range(0, n):
gears[j] += 1 if j%2==0 else -1
gears[j] %= n
stdout.write('No')
check()
``` | output | 1 | 88,838 | 3 | 177,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2. | instruction | 0 | 88,839 | 3 | 177,678 |
Tags: brute force, implementation
Correct Solution:
```
import functools as ft
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().split()))
b = [i for i in range(n)]
for i in range(1, n + 1):
a = [(a[j] + 1) % n if not j % 2 else (a[j] - 1) % n for j in range(n)]
cnt = ft.reduce(lambda x, y: x + y, [a[j] == b[j] for j in range(n)])
if cnt == n:
print("YES")
break
else:
print("NO")
``` | output | 1 | 88,839 | 3 | 177,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2. | instruction | 0 | 88,840 | 3 | 177,680 |
Tags: brute force, implementation
Correct Solution:
```
n = int(input())
g = list(map(int,input().split()))
left = g[0]
right = n-g[0]
# check left
i = 0
while i<n and (g[i]+[-left,+left][i%2])%n == i:
i += 1
if i == n:
print ("Yes")
exit()
i = 0
#(g[i]-[-left,right][i%2])%n
while i<n and (g[i]+[right,-right][i%2])%n == i:
i += 1
if i == n:
print ("Yes")
exit()
print ("No")
``` | output | 1 | 88,840 | 3 | 177,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
Submitted Solution:
```
n = int(input())
l = list(map(int,input().split()))
steps = -l[0]
l[0] = 0
for i in range(1,n):
if i%2 == 1:
l[i] = (l[i]-steps)%n
if i%2 == 0:
l[i] = l[i]+steps
if l[i] < 0:
l[i] = n+l[i]
# print(l)
if l == list(range(n)):
print("YES")
else:
print("NO")
``` | instruction | 0 | 88,841 | 3 | 177,682 |
Yes | output | 1 | 88,841 | 3 | 177,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
Submitted Solution:
```
import sys
n = int(input())
a = [int(x) for x in input().split()]
for i in range(1000):
turn = n - a[0]
ok = True
for i in range(len(a)):
a[i] = (a[i] + (turn if i % 2 == 0 else -turn)) % n
if a[i] != i:
ok = False
if ok:
print("Yes")
sys.exit(0)
print("No")
``` | instruction | 0 | 88,842 | 3 | 177,684 |
Yes | output | 1 | 88,842 | 3 | 177,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
Submitted Solution:
```
def main():
n = int(input())
a = [int(i) for i in input().split()]
d = 0 if a[0] == 0 else n - a[0]
for i in range(n):
if i % 2 == 0:
a[i] = (a[i] + d) % n
else:
a[i] = (a[i] - d + n) % n
if a == list(range(n)):
print("Yes")
else:
print("No")
main()
``` | instruction | 0 | 88,843 | 3 | 177,686 |
Yes | output | 1 | 88,843 | 3 | 177,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
Submitted Solution:
```
#----Kuzlyaev-Nikita-Codeforces-----
#------------02.04.2020-------------
alph="abcdefghijklmnopqrstuvwxyz"
#-----------------------------------
n=int(input())
a=list(map(int,input().split()))
p=(n-a[0])%n
for j in range(n):
if j%2==0:
if a[j]>j:r=n+j-a[j]
elif a[j]==j:r=0
else:
r=j-a[j]
else:
if a[j]>j:r=a[j]-j
elif a[j]==j:r=0
else:
r=a[j]+n-j
if r!=p:
print("No")
break
else:
print("Yes")
``` | instruction | 0 | 88,844 | 3 | 177,688 |
Yes | output | 1 | 88,844 | 3 | 177,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
Submitted Solution:
```
# char_to_dots = {
# 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
# 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
# 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
# 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
# 'Y': '-.--', 'Z': '--..', ' ': ' ', '0': '-----',
# '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
# '6': '-....', '7': '--...', '8': '---..', '9': '----.',
# '&': '.-...', "'": '.----.', '@': '.--.-.', ')': '-.--.-', '(': '-.--.',
# ':': '---...', ',': '--..--', '=': '-...-', '!': '-.-.--', '.': '.-.-.-',
# '-': '-....-', '+': '.-.-.', '"': '.-..-.', '?': '..--..', '/': '-..-.'
# }
#from cmath import sqrt
# def printThreads(max, steps):
# step = max // steps
# print("{")
# start = 0
# for i in range(1, steps + 1):
# print("std::thread th", i, "(sr, arr + ", start, ", arr + ", start + step, ");", sep = "")
# start += step
# for i in range(1, steps + 1):
# print("th", i, ".join();", sep = "")
# print("}")
# index = 2
# steps //= 2
# while steps >= 2:
# start = 0
# print("{")
# for i in range(1, steps + 1):
# print("std::thread th", i, "(inplace, arr + ", start, ", arr + ", start + step * (index // 2), ", arr + ", start + step * 2 * (index // 2), ");", sep = "")
# start += step * index
# for i in range(1, steps + 1):
# print("th", i, ".join();", sep = "")
# print("}")
# index *= 2
# steps //= 2
# printThreads(1000000000, 32)
from math import *
import random
def isSorted(list):
for i in range(1, len(list)):
if list[i] < list[i - 1]:
return False
return True
def stringToList(string):
return [int(i) for i in string.split(' ')]
def isTrue(list):
for i in range(4):
add = -1
for i in range(len(list)):
list[i] += add
if list[i] < 0:
list[i] = 4
elif list[i] > 4:
list[i] = 0
if add == 1:
add = -1
else:
add = 1
if isSorted(list):
return True
return False
list = stringToList("0 2 3 1")
if isTrue(list):
print("Yes")
else:
print("No")
``` | instruction | 0 | 88,845 | 3 | 177,690 |
No | output | 1 | 88,845 | 3 | 177,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
Submitted Solution:
```
n = int(input())
l = list(map(int,input().split()))
steps = -l[0]
l[0] = 0
for i in range(1,n):
if i%2 == 1:
l[i] = (l[i]-steps)%n
if i%2 == 0:
l[i] = l[i]+steps
if l[i] < 0:
l[i] = n+l[i]
print(l)
if l == list(range(n)):
print("YES")
else:
print("NO")
``` | instruction | 0 | 88,846 | 3 | 177,692 |
No | output | 1 | 88,846 | 3 | 177,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
Submitted Solution:
```
import math
import string
num = int(input())
ch = str(input())
m=2*num-2
Z="0"
od=str(num-1)
delt=str(num-1)
beta = "1"
if len(ch)<2*num-1:
for w1 in range(num-len(ch)):
ch=ch +"0"
elif len(ch)> 2*num-1:
ch =ch[0:num]
if num % 2 is 0:
for i in range (1,num):
Z=Z+" "+ str(i)
od =od +" "+str(num-1-i)
else :
for v in range (1,num):
delt = delt +" "
delt= delt +str( v -int(math.pow(-1,v)))
for k in range (1,num):
beta=beta + " "
if k +int(math.pow(-1,k)) is num :
beta =beta +"0"
else:
beta=beta+str( k +int(math.pow(-1,k)))
if num%2 is 0:
for d in range(0,m+1,2):
if eval(Z[d]) is eval(ch [d]):
if d is m:
print ("yes")
elif eval(od[d]) is eval(ch [d]):
if d is m:
print("yes")
else:
print("no")
break
else:
for d in range(0,m+1,2):
if eval(delt[d]) is eval(ch[d]):
if d is m:
print ("yes")
elif eval(beta[d]) is eval(ch [d]):
if d is m:
print ("yes")
else:
print ("no")
break
``` | instruction | 0 | 88,847 | 3 | 177,694 |
No | output | 1 | 88,847 | 3 | 177,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
Input
The first line contains integer n (1 β€ n β€ 1000) β the number of gears.
The second line contains n digits a1, a2, ..., an (0 β€ ai β€ n - 1) β the sequence of active teeth: the active tooth of the i-th gear contains number ai.
Output
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
Examples
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
Note
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
even = a[::2]
odd = a[1::2]
ans = 0
if n == 2 and len(set(a)) == 1:ans = 1
if (len(even) != len(set(even))) or (len(odd) != len(set(odd))):
ans = 1
de = 0
def rotdiff(x, y):
if (x + 2)%n == y:
return True
return False
def nordiff(x, y):
if (x - 2)%n == y:
return True
return False
for i in range(len(even) - 1):
if de == 0:
if nordiff(even[i], even[i+1]):
de = 1
elif rotdiff(even[i], even[i+1]):
de = -1
else:
ans = 1
break
else:
if de == 1:
if not nordiff(even[i], even[i+1]):
ans = 1
else:
if not rotdiff(even[i], even[i+1]):
ans = 1
de = 0
for i in range(len(odd) - 1):
if de == 0:
if nordiff(odd[i], odd[i+1]):
de = 1
elif rotdiff(odd[i], odd[i+1]):
de = -1
else:
ans = 1
break
else:
if de == 1:
if not nordiff(odd[i], odd[i+1]):
ans = 1
else:
if not rotdiff(odd[i], odd[i+1]):
ans = 1
print('No' if ans else 'Yes')
``` | instruction | 0 | 88,848 | 3 | 177,696 |
No | output | 1 | 88,848 | 3 | 177,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | instruction | 0 | 88,868 | 3 | 177,736 |
Tags: data structures, geometry, math
Correct Solution:
```
from collections import defaultdict as dc
x=int(input())
dx=dc(lambda:0)
dy=dc(lambda:0)
dxy=dc(lambda:0)
for n in range(x):
a,b=map(int,input().split())
dx[a]+=1
dy[b]+=1
dxy[(a,b)]+=1
res=0
for n in dx:
res+=int(dx[n]!=1)*(dx[n]*(dx[n]-1)//2)
for n in dy:
res+=int(dy[n]!=1)*(dy[n]*(dy[n]-1)//2)
for n in dxy:
res-=int(dxy[n]!=1)*(dxy[n]*(dxy[n]-1)//2)
print(res)
``` | output | 1 | 88,868 | 3 | 177,737 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | instruction | 0 | 88,869 | 3 | 177,738 |
Tags: data structures, geometry, math
Correct Solution:
```
n = int(input())
z=n
x={}
y={}
xy={}
ans = 0
while z:
a=0
b=0
a,b=input().split(" ")
a=int(a)
b=int(b)
try:
x[a]=x[a]+1
except:
x[a]=1
try:
y[b]=y[b]+1
except:
y[b]=1
try:
xy[(a,b)]=xy[(a,b)]+1
except:
xy[(a,b)]=1
ans+=x[a]+y[b]-xy[(a,b)]
z-=1
print(ans-n)
``` | output | 1 | 88,869 | 3 | 177,739 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | instruction | 0 | 88,870 | 3 | 177,740 |
Tags: data structures, geometry, math
Correct Solution:
```
n = int(input())
dict_x = {}
dict_y = {}
dict_xy = {}
for _ in range(n):
x, y = map(int, input().split())
try:
dict_xy[(x, y)] += 1
except KeyError:
dict_xy[(x, y)] = 1
try:
dict_x[x] += 1
except KeyError:
dict_x[x] = 1
try:
dict_y[y] += 1
except KeyError:
dict_y[y] = 1
ans = 0
for i in (*dict_x.values(), *dict_y.values()):
ans += i*(i-1)//2
for i in dict_xy.values():
ans -= i*(i-1)//2
print(ans)
``` | output | 1 | 88,870 | 3 | 177,741 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | instruction | 0 | 88,871 | 3 | 177,742 |
Tags: data structures, geometry, math
Correct Solution:
```
from sys import stdin
input = stdin.readline
n = int(input())
x, y, s, ans = dict(), dict(), dict(), 0
for i in range(n):
a, b = [int(i) for i in input().split()]
s[(a, b)] = 1 if (a, b) not in s.keys() else s[(a, b)] + 1
x[a] = 1 if a not in x.keys() else x[a] + 1
y[b] = 1 if b not in y.keys() else y[b] + 1
for k, v in x.items():
ans += v * (v - 1) // 2
for k, v in y.items():
ans += v * (v - 1) // 2
for k, v in s.items():
ans -= v * (v - 1) // 2
print(ans)
``` | output | 1 | 88,871 | 3 | 177,743 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | instruction | 0 | 88,872 | 3 | 177,744 |
Tags: data structures, geometry, math
Correct Solution:
```
n = int(input())
Dx = dict()
Dy = dict()
Dxy = dict()
for _ in range(n):
x,y = map(int,input().split())
if x in Dx:
Dx[x] += 1
else:
Dx[x] = 1
if y in Dy:
Dy[y] += 1
else:
Dy[y] = 1
if (x,y) in Dxy:
Dxy[(x,y)] += 1
else:
Dxy[(x,y)] = 1
R = dict()
for v in Dx.values():
if v in R:
R[v] += 1
else:
R[v] = 1
for v in Dy.values():
if v in R:
R[v] += 1
else:
R[v] = 1
for v in Dxy.values():
if v in R:
R[v] -= 1
else:
R[v] = -1
ans = 0
for v in R:
ans += (R[v]*v*(v-1))//2
print(ans)
``` | output | 1 | 88,872 | 3 | 177,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | instruction | 0 | 88,873 | 3 | 177,746 |
Tags: data structures, geometry, math
Correct Solution:
```
def main():
n = int(input())
xs = {}
ys = {}
xys = {}
total = 0
for i in range(n):
ab = list(map(int, input().split()))
a = ab[0]
b = ab[1]
if a in xs:
xs[a] += 1
total += xs[a]
else:
xs[a] = 0
if b in ys:
ys[b] += 1
total += ys[b]
else:
ys[b] = 0
if (a, b) in xys:
xys[(a, b)] += 1
total -= xys[(a, b)]
else:
xys[(a, b)] = 0
print(total)
if __name__ == '__main__':
main()
``` | output | 1 | 88,873 | 3 | 177,747 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | instruction | 0 | 88,874 | 3 | 177,748 |
Tags: data structures, geometry, math
Correct Solution:
```
x={}
y={}
d={}
ans=0
for i in range(int(input())):
a,b=map(int,input().split())
if a in x:
x[a]+=1
else:
x[a]=1
if b in y:
y[b]+=1
else:
y[b]=1
if (a,b) in d:
d[(a,b)]+=1
else:
d[(a,b)]=1
x=list(x.values())
y=list(y.values())
d=list(d.values())
for i in x:
ans+=(i*(i-1))//2
for i in y:
ans+=(i*(i-1))//2
for i in d:
ans-=(i*(i-1))//2
print(ans)
``` | output | 1 | 88,874 | 3 | 177,749 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | instruction | 0 | 88,875 | 3 | 177,750 |
Tags: data structures, geometry, math
Correct Solution:
```
n = int(input())
arr = list()
for i in range(n):
x, y = map(int, input().split())
arr.append((x, y))
arr.sort()
c = 0
x = 1
for i in range(n - 1):
if arr[i][0] == arr[i + 1][0]:
x += 1
else:
c += x * (x - 1) // 2
x = 1
c += x * (x - 1) // 2
x = 1
arr.sort(key = lambda T : T[1])
for i in range(n - 1):
if arr[i][1] == arr[i + 1][1]:
x += 1
else:
c += x * (x - 1) // 2
x = 1
c += x * (x - 1) // 2
x = 1
for i in range(n - 1):
if arr[i][1] == arr[i + 1][1] and arr[i][0] == arr[i + 1][0]:
x += 1
else:
c -= x * (x - 1) // 2
x = 1
c -= x * (x - 1) // 2
print(c)
``` | output | 1 | 88,875 | 3 | 177,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
from collections import defaultdict
(X, Y, P), k = (defaultdict(int) for _ in range(3)), 0
for _ in range(int(input())):
x, y = input().split()
k += X[x] + Y[y] - P[(x, y)]
X[x], Y[y], P[(x, y)] = X[x] + 1, Y[y] + 1, P[(x, y)] + 1
print(k)
``` | instruction | 0 | 88,876 | 3 | 177,752 |
Yes | output | 1 | 88,876 | 3 | 177,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
#!/usr/bin/python3
from operator import itemgetter
n = int(input())
# points = []
rows = {}
cols = {}
freq = {}
res = 0
for i in range(n):
x, y = map(int, input().split())
# points.append((x, y))
if x in cols:
cols[x].append(y)
else:
cols[x] = [y]
if y in rows:
rows[y].append(x)
else:
rows[y] = [x]
pt = (x, y)
if pt not in freq:
freq[pt] = 1
else:
freq[pt] += 1
res -= freq[pt] - 1
# points.sort(key=itemgetter(0))
for x, col in cols.items():
k = len(col)
res += k*(k-1)//2
for y, row in rows.items():
k = len(row)
res += k*(k-1)//2
print(res)
``` | instruction | 0 | 88,877 | 3 | 177,754 |
Yes | output | 1 | 88,877 | 3 | 177,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
n = int(input())
coords_x = {}
coords_y = {}
dots = []
tmp = 0
def dictappender_x(a):
try:
coords_x[a] += 1
except KeyError:
coords_x[a] = 1
def dictappender_y(a):
try:
coords_y[a] += 1
except KeyError:
coords_y[a] = 1
for i in range(n):
a, b = list(map(int, input().split()))
dots.append((a, b))
for i in range(len(dots)):
dictappender_x(dots[i][0])
dictappender_y(dots[i][1])
#print(coords_x, coords_y)
count = 0
for key, value in coords_x.items():
count += value * (value - 1) // 2
for key, value in coords_y.items():
count += value * (value - 1) // 2
coords = {}
for dot in dots:
if dot in coords:
coords[dot] += 1
else:
coords[dot] = 1
summ = 0
for key, value in coords.items():
summ += value * (value - 1) // 2
#print(summ - len(coords))
#print(count, summ, count - summ)
print(count - summ)
``` | instruction | 0 | 88,878 | 3 | 177,756 |
Yes | output | 1 | 88,878 | 3 | 177,757 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
from collections import Counter
a0 = int(input())
c = 0
xx = Counter()
yy = Counter()
xy = Counter()
for z in range(a0):
x, y = map(int, input().split())
c += xx[x] + yy[y] - xy[(x, y)]
xx[x] += 1
yy[y] += 1
xy[(x, y)] += 1
print(c)
``` | instruction | 0 | 88,879 | 3 | 177,758 |
Yes | output | 1 | 88,879 | 3 | 177,759 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.