context stringlengths 88 7.54k | groundtruth stringlengths 9 28.8k | groundtruth_language stringclasses 3 values | type stringclasses 2 values | code_test_cases listlengths 1 565 β | dataset stringclasses 6 values | code_language stringclasses 1 value | difficulty float64 0 1 β | mid stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|
Mr. Chanek has an integer represented by a string s. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit.
Mr. Chanek wants to count the number of possible integer s, where s is divisible by 25. Of course, s must not contain any leading zero. He can replace the character _ with any digit. He can also replace the character X with any digit, but it must be the same for every character X.
As a note, a leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, 0025 has two leading zeroes. An exception is the integer zero, (0 has no leading zero, but 0000 has three leading zeroes).
Input
One line containing the string s (1 β€ |s| β€ 8). The string s consists of the characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, _, and X.
Output
Output an integer denoting the number of possible integer s.
Examples
Input
25
Output
1
Input
_00
Output
9
Input
_XX
Output
9
Input
0
Output
1
Input
0_25
Output
0
Note
In the first example, the only possible s is 25.
In the second and third example, s β \{100, 200,300,400,500,600,700,800,900\}.
In the fifth example, all possible s will have at least one leading zero.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | s = input()
ways = 0
if len(s) == 1:
if s in ['_', 'X', '0']:
ways = 1
elif len(s) == 2:
if s in ['25', '50', '75']:
ways = 1
elif s in ['__', '_X', 'X_']:
ways = 3
elif s == '_0':
ways = 1
elif s in ['_5', 'X5']:
ways = 2
elif s in ['2_', '5_', '7_', '2X', '5X', '7X', 'X0']:
ways = 1
else:
d = s[-2:]
s = s[:-2]
if d in ['00', '25', '50', '75', '__', '_X', 'X_', 'XX', '_0', '_5', '0_', '2_', '5_', '7_', 'X0', 'X5', '0X', '2X', '5X', '7X']:
ways = 1
xfound = False
if d in ['__', '_X', 'X_']:
ways *= 4
elif d in ['_0', '_5', 'X0', 'X5']:
ways *= 2
if 'X' in d:
xfound = True
if s[0] == '_' or (s[0] == 'X' and not xfound):
ways *= 9
if s[0] == 'X':
xfound = True
if s[0] == 'X' and d in ['_X', 'X_', 'XX', '0X', 'X0', '5X']:
if d == 'X0':
ways //= 2
elif d in ['_X', 'X_']:
ways //= 4
if d == 'X_':
ways *= 3
else:
ways *= 2
else:
ways = 0
if s[0] == '0':
ways = 0
for c in s[1:]:
if c == '_':
ways *= 10
elif c == 'X' and not xfound:
ways *= 10
xfound = True
print(ways) | python | code_algorithm | [
{
"input": "0\n",
"output": "1\n"
},
{
"input": "_XX\n",
"output": "9\n"
},
{
"input": "_00\n",
"output": "9\n"
},
{
"input": "0_25\n",
"output": "0\n"
},
{
"input": "25\n",
"output": "1\n"
},
{
"input": "X\n",
"output": "1\n"
},
{
"input":... | code_contests | python | 0 | ed6f1257ca12e3c82eb8f21afb8ef487 |
Mr. Chanek wants to knit a batik, a traditional cloth from Indonesia. The cloth forms a grid a with size n Γ m. There are k colors, and each cell in the grid can be one of the k colors.
Define a sub-rectangle as an ordered pair of two cells ((x_1, y_1), (x_2, y_2)), denoting the top-left cell and bottom-right cell (inclusively) of a sub-rectangle in a. Two sub-rectangles ((x_1, y_1), (x_2, y_2)) and ((x_3, y_3), (x_4, y_4)) have the same pattern if and only if the following holds:
* they have the same width (x_2 - x_1 = x_4 - x_3);
* they have the same height (y_2 - y_1 = y_4 - y_3);
* for every pair (i, j) where 0 β€ i β€ x_2 - x_1 and 0 β€ j β€ y_2 - y_1, the color of cells (x_1 + i, y_1 + j) and (x_3 + i, y_3 + j) are equal.
Count the number of possible batik color combinations, such that the subrectangles ((a_x, a_y),(a_x + r - 1, a_y + c - 1)) and ((b_x, b_y),(b_x + r - 1, b_y + c - 1)) have the same pattern.
Output the answer modulo 10^9 + 7.
Input
The first line contains five integers n, m, k, r, and c (1 β€ n, m β€ 10^9, 1 β€ k β€ 10^9, 1 β€ r β€ min(10^6, n), 1 β€ c β€ min(10^6, m)) β the size of the batik, the number of colors, and size of the sub-rectangle.
The second line contains four integers a_x, a_y, b_x, and b_y (1 β€ a_x, b_x β€ n, 1 β€ a_y, b_y β€ m) β the top-left corners of the first and second sub-rectangle. Both of the sub-rectangles given are inside the grid (1 β€ a_x + r - 1, b_x + r - 1 β€ n, 1 β€ a_y + c - 1, b_y + c - 1 β€ m).
Output
Output an integer denoting the number of possible batik color combinations modulo 10^9 + 7.
Examples
Input
3 3 2 2 2
1 1 2 2
Output
32
Input
4 5 170845 2 2
1 4 3 1
Output
756680455
Note
The following are all 32 possible color combinations in the first example.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, m, k, r, c = map(int, input().split())
ax, ay, bx, by = map(int, input().split())
p = n * m
if ax != bx or ay != by:
p -= r * c
print(pow(k, p, 1000000007)) | python | code_algorithm | [
{
"input": "4 5 170845 2 2\n1 4 3 1\n",
"output": "756680455\n"
},
{
"input": "3 3 2 2 2\n1 1 2 2\n",
"output": "32\n"
},
{
"input": "997824195 298198038 671030405 831526 973640\n694897941 219757278 695597597 220039071\n",
"output": "885735196\n"
},
{
"input": "78 15 96708421... | code_contests | python | 0 | d33e36bf94b08b4d06c6cb4c1381cc4f |
Casimir has a rectangular piece of paper with a checkered field of size n Γ m. Initially, all cells of the field are white.
Let us denote the cell with coordinates i vertically and j horizontally by (i, j). The upper left cell will be referred to as (1, 1) and the lower right cell as (n, m).
Casimir draws ticks of different sizes on the field. A tick of size d (d > 0) with its center in cell (i, j) is drawn as follows:
1. First, the center cell (i, j) is painted black.
2. Then exactly d cells on the top-left diagonally to the center and exactly d cells on the top-right diagonally to the center are also painted black.
3. That is all the cells with coordinates (i - h, j Β± h) for all h between 0 and d are painted. In particular, a tick consists of 2d + 1 black cells.
An already painted cell will remain black if painted again. Below you can find an example of the 4 Γ 9 box, with two ticks of sizes 2 and 3.
<image>
You are given a description of a checkered field of size n Γ m. Casimir claims that this field came about after he drew some (possibly 0) ticks on it. The ticks could be of different sizes, but the size of each tick is at least k (that is, d β₯ k for all the ticks).
Determine whether this field can indeed be obtained by drawing some (possibly none) ticks of sizes d β₯ k or not.
Input
The first line contains an integer t (1 β€ t β€ 100) β the number test cases.
The following lines contain the descriptions of the test cases.
The first line of the test case description contains the integers n, m, and k (1 β€ k β€ n β€ 10; 1 β€ m β€ 19) β the field size and the minimum size of the ticks that Casimir drew. The following n lines describe the field: each line consists of m characters either being '.' if the corresponding cell is not yet painted or '*' otherwise.
Output
Print t lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if the given field can be obtained by drawing ticks of at least the given size and NO otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).
Example
Input
8
2 3 1
*.*
...
4 9 2
*.*.*...*
.*.*...*.
..*.*.*..
.....*...
4 4 1
*.*.
****
.**.
....
5 5 1
.....
*...*
.*.*.
..*.*
...*.
5 5 2
.....
*...*
.*.*.
..*.*
...*.
4 7 1
*.....*
.....*.
..*.*..
...*...
3 3 1
***
***
***
3 5 1
*...*
.***.
.**..
Output
NO
YES
YES
YES
NO
NO
NO
NO
Note
The first sample test case consists of two asterisks neither of which can be independent ticks since ticks of size 0 don't exist.
The second sample test case is already described in the statement (check the picture in the statement). This field can be obtained by drawing ticks of sizes 2 and 3, as shown in the figure.
The field in the third sample test case corresponds to three ticks of size 1. Their center cells are marked with \color{blue}{blue}, \color{red}{red} and \color{green}{green} colors: *.*.
---
*\color{blue}{*}**
.\color{green}{*}\color{red}{*}.
....
The field in the fourth sample test case could have been obtained by drawing two ticks of sizes 1 and 2. Their vertices are marked below with \color{blue}{blue} and \color{red}{red} colors respectively: .....
---
*...*
.*.*.
..\color{red}{*}.*
...\color{blue}{*}.
The field in the fifth sample test case can not be obtained because k = 2, and the last asterisk in the fourth row from the top with coordinates (4, 5) can only be a part of a tick of size 1.
The field in the sixth sample test case can not be obtained because the top left asterisk (1, 1) can't be an independent tick, since the sizes of the ticks must be positive, and cannot be part of a tick with the center cell in the last row, since it is separated from it by a gap (a point, '.') in (2, 2).
In the seventh sample test case, similarly, the field can not be obtained by the described process because the asterisks with coordinates (1, 2) (second cell in the first row), (3, 1) and (3, 3) (leftmost and rightmost cells in the bottom) can not be parts of any ticks.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict, deque
from io import BytesIO, IOBase
from itertools import permutations
import string
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
self.BUFSIZE = 8192
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def get_int():
return int(input())
def get_ints():
return list(map(int, input().split(' ')))
def get_int_grid(n):
return [get_ints() for _ in range(n)]
def get_str():
return input().strip()
def get_strs():
return get_str().split(' ')
def flat_list(arr):
return [item for subarr in arr for item in subarr]
def yes_no(b):
if b:
return "YES"
else:
return "NO"
def binary_search(good, left, right, delta=1, right_true=False):
"""
Performs binary search
----------
Parameters
----------
:param good: Function used to perform the binary search
:param left: Starting value of left limit
:param right: Starting value of the right limit
:param delta: Margin of error, defaults value of 1 for integer binary search
:param right_true: Boolean, for whether the right limit is the true invariant
:return: Returns the most extremal value interval [left, right] which is good function evaluates to True,
alternatively returns False if no such value found
"""
limits = [left, right]
while limits[1] - limits[0] > delta:
if delta == 1:
mid = sum(limits) // 2
else:
mid = sum(limits) / 2
if good(mid):
limits[int(right_true)] = mid
else:
limits[int(~right_true)] = mid
if good(limits[int(right_true)]):
return limits[int(right_true)]
else:
return False
def prefix_sums(a):
p = [0]
for x in a:
p.append(p[-1] + x)
return p
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def solve_c():
n, m, k = get_ints()
h = []
s = set()
SL = SortedList([])
chk = set()
rem = set()
for i in range(n):
s = get_str()
for j in range(m):
if s[j] == '*':
chk.add((i, j))
rem.add((i, j))
for i, j in rem:
s = 0
while (i - s, j + s) in rem and (i - s, j - s) in rem:
s += 1
s -= 1
if s >= k:
for d in range(s + 1):
chk.discard((i - d, j + d))
chk.discard((i - d, j - d))
if len(chk) == 0:
return "YES"
else:
return "NO"
t = get_int()
for _ in range(t):
print(solve_c())
| python | code_algorithm | [
{
"input": "8\n2 3 1\n*.*\n...\n4 9 2\n*.*.*...*\n.*.*...*.\n..*.*.*..\n.....*...\n4 4 1\n*.*.\n****\n.**.\n....\n5 5 1\n.....\n*...*\n.*.*.\n..*.*\n...*.\n5 5 2\n.....\n*...*\n.*.*.\n..*.*\n...*.\n4 7 1\n*.....*\n.....*.\n..*.*..\n...*...\n3 3 1\n***\n***\n***\n3 5 1\n*...*\n.***.\n.**..\n",
"output": "NO\... | code_contests | python | 0 | ca88f3cd16ba3a4859a25088141e9b4f |
CQXYM is counting permutations length of 2n.
A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
A permutation p(length of 2n) will be counted only if the number of i satisfying p_i<p_{i+1} is no less than n. For example:
* Permutation [1, 2, 3, 4] will count, because the number of such i that p_i<p_{i+1} equals 3 (i = 1, i = 2, i = 3).
* Permutation [3, 2, 1, 4] won't count, because the number of such i that p_i<p_{i+1} equals 1 (i = 3).
CQXYM wants you to help him to count the number of such permutations modulo 1000000007 (10^9+7).
In addition, [modulo operation](https://en.wikipedia.org/wiki/Modulo_operation) is to get the remainder. For example:
* 7 mod 3=1, because 7 = 3 β
2 + 1,
* 15 mod 4=3, because 15 = 4 β
3 + 3.
Input
The input consists of multiple test cases.
The first line contains an integer t (t β₯ 1) β the number of test cases. The description of the test cases follows.
Only one line of each test case contains an integer n(1 β€ n β€ 10^5).
It is guaranteed that the sum of n over all test cases does not exceed 10^5
Output
For each test case, print the answer in a single line.
Example
Input
4
1
2
9
91234
Output
1
12
830455698
890287984
Note
n=1, there is only one permutation that satisfies the condition: [1,2].
In permutation [1,2], p_1<p_2, and there is one i=1 satisfy the condition. Since 1 β₯ n, this permutation should be counted. In permutation [2,1], p_1>p_2. Because 0<n, this permutation should not be counted.
n=2, there are 12 permutations: [1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,3,1,4],[2,3,4,1],[2,4,1,3],[3,1,2,4],[3,4,1,2],[4,1,2,3].
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import stdin, gettrace
if gettrace():
def inputi():
return input()
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
LIMIT = 200001
MOD = 1000000007
def solve(factorial):
n = int(input())
print( (factorial[2*n]*pow(2, MOD-2, MOD))%MOD)
def main():
factorial = [1]
for i in range(1, LIMIT):
factorial.append((factorial[-1]*i)%MOD)
t = int(input())
for _ in range(t):
solve(factorial)
if __name__ == "__main__":
main()
| python | code_algorithm | [
{
"input": "4\n1\n2\n9\n91234\n",
"output": "1\n12\n830455698\n890287984\n"
},
{
"input": "2\n99997\n3\n",
"output": "979296788\n360\n"
},
{
"input": "14\n13633\n739\n4\n1\n23481\n279\n5113\n2013\n48785\n12\n44\n5766\n3\n127\n",
"output": "265272552\n34141923\n20160\n1\n405591801\n64... | code_contests | python | 0 | dded87415d219981884917305a6a7adc |
CQXYM wants to create a connected undirected graph with n nodes and m edges, and the diameter of the graph must be strictly less than k-1. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most one edge).
The diameter of a graph is the maximum distance between any two nodes.
The distance between two nodes is the minimum number of the edges on the path which endpoints are the two nodes.
CQXYM wonders whether it is possible to create such a graph.
Input
The input consists of multiple test cases.
The first line contains an integer t (1 β€ t β€ 10^5) β the number of test cases. The description of the test cases follows.
Only one line of each test case contains three integers n(1 β€ n β€ 10^9), m, k (0 β€ m,k β€ 10^9).
Output
For each test case, print YES if it is possible to create the graph, or print NO if it is impossible. You can print each letter in any case (upper or lower).
Example
Input
5
1 0 3
4 5 3
4 6 3
5 4 1
2 1 1
Output
YES
NO
YES
NO
NO
Note
In the first test case, the graph's diameter equal to 0.
In the second test case, the graph's diameter can only be 2.
In the third test case, the graph's diameter can only be 1.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | for _ in range(int(input())):n, m, k = map(int, input().split());print('YES') if (k == 3 and m == (n * (n - 1)) // 2) or (k > 3 and m >= n - 1 and m <= (n * (n - 1)) // 2) or (n == 1 and m == 0 and k > 1) else print('NO') | python | code_algorithm | [
{
"input": "5\n1 0 3\n4 5 3\n4 6 3\n5 4 1\n2 1 1\n",
"output": "YES\nNO\nYES\nNO\nNO\n"
},
{
"input": "1\n1 0 0\n",
"output": "NO\n"
},
{
"input": "1\n5 7 0\n",
"output": "NO\n"
},
{
"input": "5\n1 0 2\n1 0 1\n5 20 3\n5 20 4\n5 20 5\n",
"output": "YES\nNO\nNO\nNO\nNO\n"
... | code_contests | python | 0 | c778c5080a0af3985dbf796423726d96 |
The problem statement looms below, filling you with determination.
Consider a grid in which some cells are empty and some cells are filled. Call a cell in this grid exitable if, starting at that cell, you can exit the grid by moving up and left through only empty cells. This includes the cell itself, so all filled in cells are not exitable. Note that you can exit the grid from any leftmost empty cell (cell in the first column) by going left, and from any topmost empty cell (cell in the first row) by going up.
Let's call a grid determinable if, given only which cells are exitable, we can exactly determine which cells are filled in and which aren't.
You are given a grid a of dimensions n Γ m , i. e. a grid with n rows and m columns. You need to answer q queries (1 β€ q β€ 2 β
10^5). Each query gives two integers x_1, x_2 (1 β€ x_1 β€ x_2 β€ m) and asks whether the subgrid of a consisting of the columns x_1, x_1 + 1, β¦, x_2 - 1, x_2 is determinable.
Input
The first line contains two integers n, m (1 β€ n, m β€ 10^6, nm β€ 10^6) β the dimensions of the grid a.
n lines follow. The y-th line contains m characters, the x-th of which is 'X' if the cell on the intersection of the the y-th row and x-th column is filled and "." if it is empty.
The next line contains a single integer q (1 β€ q β€ 2 β
10^5) β the number of queries.
q lines follow. Each line contains two integers x_1 and x_2 (1 β€ x_1 β€ x_2 β€ m), representing a query asking whether the subgrid of a containing the columns x_1, x_1 + 1, β¦, x_2 - 1, x_2 is determinable.
Output
For each query, output one line containing "YES" if the subgrid specified by the query is determinable and "NO" otherwise. The output is case insensitive (so "yEs" and "No" will also be accepted).
Example
Input
4 5
..XXX
...X.
...X.
...X.
5
1 3
3 3
4 5
5 5
1 5
Output
YES
YES
NO
YES
NO
Note
For each query of the example, the corresponding subgrid is displayed twice below: first in its input format, then with each cell marked as "E" if it is exitable and "N" otherwise.
For the first query:
..X EEN
... EEE
... EEE
... EEE
For the second query:
X N
. E
. E
. E
Note that you can exit the grid by going left from any leftmost cell (or up from any topmost cell); you do not need to reach the top left corner cell to exit the grid.
For the third query:
XX NN
X. NN
X. NN
X. NN
This subgrid cannot be determined only from whether each cell is exitable, because the below grid produces the above "exitability grid" as well:
XX
XX
XX
XX
For the fourth query:
X N
. E
. E
. E
For the fifth query:
..XXX EENNN
...X. EEENN
...X. EEENN
...X. EEENN
This query is simply the entire grid. It cannot be determined only from whether each cell is exitable because the below grid produces the above "exitability grid" as well:
..XXX
...XX
...XX
...XX
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | # SHRi GANESHA author: Kunal Verma #
import os
import sys
from collections import defaultdict, Counter
from io import BytesIO, IOBase
from math import gcd
def lcm(a, b):
return (a * b) // gcd(a, b)
'''
mod = 10 ** 9 + 7
fac = [1]
for i in range(1, 2 * 10 ** 5 + 1):
fac.append((fac[-1] * i) % mod)
fac_in = [pow(fac[-1], mod - 2, mod)]
for i in range(2 * 10 ** 5, 0, -1):
fac_in.append((fac_in[-1] * i) % mod)
fac_in.reverse()
def comb(a, b):
if a < b:
return 0
return (fac[a] * fac_in[b] * fac_in[a - b]) % mod
'''
# MAXN = 10000004
# spf = [0 for i in range(MAXN)]
# adj = [[] for i in range(MAXN)]
def sieve():
global spf, adj, MAXN
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(2, MAXN):
if i * i > MAXN:
break
if (spf[i] == i):
for j in range(i * i, MAXN, i):
if (spf[j] == j):
spf[j] = i
def getdistinctFactorization(n):
global adj, spf, MAXN
for i in range(1, n + 1):
index = 1
x = i
if (x != 1):
adj[i].append(spf[x])
x = x // spf[x]
while (x != 1):
if (adj[i][index - 1] != spf[x]):
adj[i].append(spf[x])
index += 1
x = x // spf[x]
def printDivisors(n):
i = 2
z = [1, n]
while i <= sqrt(n):
if (n % i == 0):
if (n / i == i):
z.append(i)
else:
z.append(i)
z.append(n // i)
i = i + 1
return z
def create(n, x, f):
pq = len(bin(n)[2:])
if f == 0:
tt = min
else:
tt = max
dp = [[inf] * n for _ in range(pq)]
dp[0] = x
for i in range(1, pq):
for j in range(n - (1 << i) + 1):
dp[i][j] = tt(dp[i - 1][j], dp[i - 1][j + (1 << (i - 1))])
return dp
def enquiry(l, r, dp, f):
if l > r:
return inf if not f else -inf
if f == 1:
tt = max
else:
tt = min
pq1 = len(bin(r - l + 1)[2:]) - 1
return tt(dp[pq1][l], dp[pq1][r - (1 << pq1) + 1])
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
x = []
for i in range(2, n + 1):
if prime[i]:
x.append(i)
return x
def main():
n,m=map(int,input().split())
s=[input().strip() for i in range(n)]
dp=[0]*(m)
for i in range(m-1,0,-1):
for j in range(1,n):
if s[j-1][i]=='X' and s[j][i-1]=="X":
dp[i]=1
for i in range(1,m):
dp[i]+=dp[i-1]
for i in range(int(input())):
xx,yy=map(int,input().split())
if xx==yy:
print("YES")
else:
yy-=1
xx-=1
if dp[yy]-dp[xx]>0:
print("NO")
else:
print("YES")
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main() | python | code_algorithm | [
{
"input": "4 5\n..XXX\n...X.\n...X.\n...X.\n5\n1 3\n3 3\n4 5\n5 5\n1 5\n",
"output": "YES\nYES\nNO\nYES\nNO\n"
},
{
"input": "3 3\n...\nXXX\nXX.\n10\n2 3\n1 2\n2 2\n1 3\n2 3\n1 2\n1 3\n1 3\n2 3\n1 1\n",
"output": "NO\nNO\nYES\nNO\nNO\nNO\nNO\nNO\nNO\nYES\n"
},
{
"input": "1 1\n.\n1\n1 1... | code_contests | python | 0 | 027ae5229e7bff4483923b232d817be2 |
Omkar is creating a mosaic using colored square tiles, which he places in an n Γ n grid. When the mosaic is complete, each cell in the grid will have either a glaucous or sinoper tile. However, currently he has only placed tiles in some cells.
A completed mosaic will be a mastapeece if and only if each tile is adjacent to exactly 2 tiles of the same color (2 tiles are adjacent if they share a side.) Omkar wants to fill the rest of the tiles so that the mosaic becomes a mastapeece. Now he is wondering, is the way to do this unique, and if it is, what is it?
Input
The first line contains a single integer n (1 β€ n β€ 2000).
Then follow n lines with n characters in each line. The i-th character in the j-th line corresponds to the cell in row i and column j of the grid, and will be S if Omkar has placed a sinoper tile in this cell, G if Omkar has placed a glaucous tile, . if it's empty.
Output
On the first line, print UNIQUE if there is a unique way to get a mastapeece, NONE if Omkar cannot create any, and MULTIPLE if there is more than one way to do so. All letters must be uppercase.
If you print UNIQUE, then print n additional lines with n characters in each line, such that the i-th character in the j^{th} line is S if the tile in row i and column j of the mastapeece is sinoper, and G if it is glaucous.
Examples
Input
4
S...
..G.
....
...S
Output
MULTIPLE
Input
6
S.....
....G.
..S...
.....S
....G.
G.....
Output
NONE
Input
10
.S....S...
..........
...SSS....
..........
..........
...GS.....
....G...G.
..........
......G...
..........
Output
UNIQUE
SSSSSSSSSS
SGGGGGGGGS
SGSSSSSSGS
SGSGGGGSGS
SGSGSSGSGS
SGSGSSGSGS
SGSGGGGSGS
SGSSSSSSGS
SGGGGGGGGS
SSSSSSSSSS
Input
1
.
Output
NONE
Note
For the first test case, Omkar can make the mastapeeces
SSSS
SGGS
SGGS
SSSS
and
SSGG
SSGG
GGSS
GGSS.
For the second test case, it can be proven that it is impossible for Omkar to add tiles to create a mastapeece.
For the third case, it can be proven that the given mastapeece is the only mastapeece Omkar can create by adding tiles.
For the fourth test case, it's clearly impossible for the only tile in any mosaic Omkar creates to be adjacent to two tiles of the same color, as it will be adjacent to 0 tiles total.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
o = {'G':'S', 'S':'G'};n = int(input());d = [list(input()[:n]) for _ in range(n)];f = [1] * (n * n);finished = 1
if n % 2: print('NONE'); sys.exit()
x = [''] * (n // 2)
def findt(i, j): return abs(j - i) // 2 if (j - i) % 2 else min(i + j, 2 * (n - 1) - j - i) // 2
def findr(i, j, t):
if (j - i) % 2: return o[t] if min(i, j) % 2 else t
else:
if i + j < n: return o[t] if i % 2 else t
else: return t if i % 2 else o[t]
for i in range(n):
for j in range(n):
if d[i][j] != '.':
t = findt(i, j);r = findr(i, j, d[i][j])
if x[t] == o[r]: print('NONE'); sys.exit()
else: x[t] = r
for i in range(n // 2):
if not x[i]: print('MULTIPLE'); sys.exit()
for i in range(n):
for j in range(n):d[i][j] = findr(i, j, x[findt(i, j)])
print('UNIQUE')
print('\n'.join(''.join(d[i]) for i in range(n))) | python | code_algorithm | [
{
"input": "10\n.S....S...\n..........\n...SSS....\n..........\n..........\n...GS.....\n....G...G.\n..........\n......G...\n..........\n",
"output": "UNIQUE\nSSSSSSSSSS\nSGGGGGGGGS\nSGSSSSSSGS\nSGSGGGGSGS\nSGSGSSGSGS\nSGSGSSGSGS\nSGSGGGGSGS\nSGSSSSSSGS\nSGGGGGGGGS\nSSSSSSSSSS\n"
},
{
"input": "4\nS.... | code_contests | python | 0 | 7340efb269e595e32d5cd4256348800d |
It is the easy version of the problem. The difference is that in this version, there are no nodes with already chosen colors.
Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?
You have a perfect binary tree of 2^k - 1 nodes β a binary tree where all vertices i from 1 to 2^{k - 1} - 1 have exactly two children: vertices 2i and 2i + 1. Vertices from 2^{k - 1} to 2^k - 1 don't have any children. You want to color its vertices with the 6 Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).
Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube.
<image>| <image>
---|---
A picture of Rubik's cube and its 2D map.
More formally:
* a white node can not be neighboring with white and yellow nodes;
* a yellow node can not be neighboring with white and yellow nodes;
* a green node can not be neighboring with green and blue nodes;
* a blue node can not be neighboring with green and blue nodes;
* a red node can not be neighboring with red and orange nodes;
* an orange node can not be neighboring with red and orange nodes;
You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.
The answer may be too large, so output the answer modulo 10^9+7.
Input
The first and only line contains the integers k (1 β€ k β€ 60) β the number of levels in the perfect binary tree you need to color.
Output
Print one integer β the number of the different colorings modulo 10^9+7.
Examples
Input
3
Output
24576
Input
14
Output
934234
Note
In the picture below, you can see one of the correct colorings of the first example.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
vid = 6
k = 2
m = int(1e9 + 7)
for i in range(n - 1):
vid = (vid * pow(4, k, m)) % m
k *= 2
print(vid)
| python | code_algorithm | [
{
"input": "14\n",
"output": "934234\n"
},
{
"input": "3\n",
"output": "24576\n"
},
{
"input": "50\n",
"output": "902552662\n"
},
{
"input": "60\n",
"output": "937481864\n"
},
{
"input": "40\n",
"output": "622757975\n"
},
{
"input": "10\n",
"output... | code_contests | python | 0 | 03949d61d7e32aef9a92ff98a89330ef |
It is the hard version of the problem. The difference is that in this version, there are nodes with already chosen colors.
Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?
You have a perfect binary tree of 2^k - 1 nodes β a binary tree where all vertices i from 1 to 2^{k - 1} - 1 have exactly two children: vertices 2i and 2i + 1. Vertices from 2^{k - 1} to 2^k - 1 don't have any children. You want to color its vertices with the 6 Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).
Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube.
<image>| <image>
---|---
A picture of Rubik's cube and its 2D map.
More formally:
* a white node can not be neighboring with white and yellow nodes;
* a yellow node can not be neighboring with white and yellow nodes;
* a green node can not be neighboring with green and blue nodes;
* a blue node can not be neighboring with green and blue nodes;
* a red node can not be neighboring with red and orange nodes;
* an orange node can not be neighboring with red and orange nodes;
However, there are n special nodes in the tree, colors of which are already chosen.
You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.
The answer may be too large, so output the answer modulo 10^9+7.
Input
The first line contains the integers k (1 β€ k β€ 60) β the number of levels in the perfect binary tree you need to color.
The second line contains the integer n (1 β€ n β€ min(2^k - 1, 2000)) β the number of nodes, colors of which are already chosen.
The next n lines contains integer v (1 β€ v β€ 2^k - 1) and string s β the index of the node and the color of the node (s is one of the white, yellow, green, blue, red and orange).
It is guaranteed that each node v appears in the input at most once.
Output
Print one integer β the number of the different colorings modulo 10^9+7.
Examples
Input
3
2
5 orange
2 white
Output
1024
Input
2
2
1 white
2 white
Output
0
Input
10
3
1 blue
4 red
5 orange
Output
328925088
Note
In the picture below, you can see one of the correct colorings of the first test example.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import io,os
#input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = 10**9 + 7
colors = {'white':0,'yellow':0,'green':1,'blue':1,'red':2,'orange':2}
def getnext(index,n,colored,dic,layer):
if layer==n:
if index not in dic: return [2,2,2]
else:
dic[index][colored[index]] += 1
return dic[index]
if index not in dic:
rest = n - layer
sub = pow(2,(1<<(rest+2))-3, M )
# print(index,sub)
return [sub,sub,sub]
left = getnext(2*index,n,colored,dic,layer+1)
right = getnext(2*index+1,n,colored,dic,layer+1)
# print(left,right)
if index in colored:
for i in range(3):
if i != colored[index]: continue
dic[index][i] = ( sum(left) - left[i] ) * (sum(right) - right[i])
dic[index][i] = dic[index][i] % M
else:
for i in range(3):
dic[index][i] = 2 * ( sum(left) - left[i] ) * (sum(right) - right[i])
dic[index][i] = dic[index][i] % M
return dic[index]
def main(t):
M = 10**9 + 7
n = int(input())
q = int(input())
dic = {}
colored = {}
for _ in range(q):
i, color = input().split()
i = int(i)
colored[i] = colors[color]
while i>0:
if i not in dic: dic[i] = [0,0,0]
i = i >> 1
ans = getnext(1,n,colored,dic,1)
# print(dic)
print(sum(ans)%M)
main(1)
| python | code_algorithm | [
{
"input": "10\n3\n1 blue\n4 red\n5 orange\n",
"output": "328925088\n"
},
{
"input": "3\n2\n5 orange\n2 white\n",
"output": "1024\n"
},
{
"input": "2\n2\n1 white\n2 white\n",
"output": "0\n"
},
{
"input": "5\n9\n31 yellow\n30 green\n26 yellow\n13 red\n2 red\n22 white\n12 red\... | code_contests | python | 0 | 013e36f8f3dee7c47acbe89bf885a328 |
You are given a matrix, consisting of n rows and m columns. The rows are numbered top to bottom, the columns are numbered left to right.
Each cell of the matrix can be either free or locked.
Let's call a path in the matrix a staircase if it:
* starts and ends in the free cell;
* visits only free cells;
* has one of the two following structures:
1. the second cell is 1 to the right from the first one, the third cell is 1 to the bottom from the second one, the fourth cell is 1 to the right from the third one, and so on;
2. the second cell is 1 to the bottom from the first one, the third cell is 1 to the right from the second one, the fourth cell is 1 to the bottom from the third one, and so on.
In particular, a path, consisting of a single cell, is considered to be a staircase.
Here are some examples of staircases:
<image>
Initially all the cells of the matrix are free.
You have to process q queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free.
Print the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.
Input
The first line contains three integers n, m and q (1 β€ n, m β€ 1000; 1 β€ q β€ 10^4) β the sizes of the matrix and the number of queries.
Each of the next q lines contains two integers x and y (1 β€ x β€ n; 1 β€ y β€ m) β the description of each query.
Output
Print q integers β the i-th value should be equal to the number of different staircases after i queries. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.
Examples
Input
2 2 8
1 1
1 1
1 1
2 2
1 1
1 2
2 1
1 1
Output
5
10
5
2
5
3
1
0
Input
3 4 10
1 4
1 2
2 3
1 2
2 3
3 2
1 3
3 4
1 3
3 1
Output
49
35
24
29
49
39
31
23
29
27
Input
1000 1000 2
239 634
239 634
Output
1332632508
1333333000
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | ''' E. Staircases
https://codeforces.com/contest/1598/problem/E
'''
import sys
input = sys.stdin.readline
output = sys.stdout.write
def solve(R, C, Q, queries):
blocked = [[0]*C for _ in range(R)]
# total staircases if no cell blocked
res = R*C # 1-block
for c in range(C): # right-down from row 0
for ln in range(1, R+C+1):
nr = ln // 2
nc = c + (ln+1) // 2
if nr >= R or nc >= C: break
res += ln
for r in range(R): # down-right from col 0
for ln in range(1, R+C+1):
nr = r + (ln+1) // 2
nc = ln // 2
if nr >= R or nc >= C: break
res += ln
# each query (qr, qc) changes total by num staircases passing through it
for qr, qc in queries:
# num staircases passing through (qr, qc)
change = 1
# type 1
r, c = qr, qc
up = down = 0
for ln in range(1, R+C+1): # go farthest down-right from (qr, qc)
nr = r + ln//2
nc = c + (ln+1)//2
if nr >= R or nc >= C or blocked[nr][nc]: break
down += 1
for ln in range(1, R+C+1): # left-up
nr = r - (ln+1)//2
nc = c - ln//2
if nr < 0 or nc < 0 or blocked[nr][nc]: break
up += 1
change += up + down + up * down
# type 2
r, c = qr, qc
up = down = 0
for ln in range(1, R+C+1): # right-down
nr = r + (ln+1)//2
nc = c + ln//2
if nr >= R or nc >= C or blocked[nr][nc]: break
down += 1
for ln in range(1, R+C+1): # up-left
nr = r - ln//2
nc = c - (ln+1)//2
if nr < 0 or nc < 0 or blocked[nr][nc]: break
up += 1
change += up + down + up * down
# add or subtract to total
res += change if blocked[qr][qc] else -change
blocked[qr][qc] ^= 1
output(str(res) + '\n')
def main():
N, M, Q = list(map(int, input().split()))
queries = []
for _ in range(Q):
x, y = list(map(int, input().split()))
queries.append((x-1, y-1))
solve(N, M, Q, queries)
if __name__ == '__main__':
main()
| python | code_algorithm | [
{
"input": "3 4 10\n1 4\n1 2\n2 3\n1 2\n2 3\n3 2\n1 3\n3 4\n1 3\n3 1\n",
"output": "49\n35\n24\n29\n49\n39\n31\n23\n29\n27\n"
},
{
"input": "1000 1000 2\n239 634\n239 634\n",
"output": "1332632508\n1333333000\n"
},
{
"input": "2 2 8\n1 1\n1 1\n1 1\n2 2\n1 1\n1 2\n2 1\n1 1\n",
"output... | code_contests | python | 0 | e4315068752313a050d2199207c8eaa7 |
Little Johnny Bubbles enjoys spending hours in front of his computer playing video games. His favorite game is Bubble Strike, fast-paced bubble shooting online game for two players.
Each game is set in one of the N maps, each having different terrain configuration. First phase of each game decides on which map the game will be played. The game system randomly selects three maps and shows them to the players. Each player must pick one of those three maps to be discarded. The game system then randomly selects one of the maps that were not picked by any of the players and starts the game.
Johnny is deeply enthusiastic about the game and wants to spend some time studying maps, thus increasing chances to win games played on those maps. However, he also needs to do his homework, so he does not have time to study all the maps. That is why he asked himself the following question: "What is the minimum number of maps I have to study, so that the probability to play one of those maps is at least P"?
Can you help Johnny find the answer for this question? You can assume Johnny's opponents do not know him, and they will randomly pick maps.
Input
The first line contains two integers N (3 β€ N β€ 10^{3}) and P (0 β€ P β€ 1) β total number of maps in the game and probability to play map Johnny has studied. P will have at most four digits after the decimal point.
Output
Output contains one integer number β minimum number of maps Johnny has to study.
Example
Input
7 1.0000
Output
6
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` |
n,target = map(float,input().split())
n = int(n)
def getprob(study):
tot = n*(n-1)*(n-2)//6
case1 = study*(study-1)*(study-2)//6
case2 = study*(study-1)*(n-study)//2
case3 = study*(n-study)*(n-study-1)//2
return (case1+case2+case3*0.5)*1.0/tot
front = 0
rear = n
while front<rear:
mid = (front+rear)//2
p = getprob(mid)
# print(mid,p)
if p < target: front = mid + 1
else: rear = mid
print(front)
| python | code_algorithm | [
{
"input": "7 1.0000\n",
"output": "6\n"
},
{
"input": "956 0.9733\n",
"output": "826\n"
},
{
"input": "444 0.0265\n",
"output": "8\n"
},
{
"input": "267 0.4122\n",
"output": "76\n"
},
{
"input": "840 0.5672\n",
"output": "336\n"
},
{
"input": "937 0.8... | code_contests | python | 0 | 37c5323b7eec8e56d57a3d9db5cb7b1b |
Alice and Bob are playing a game. They are given an array A of length N. The array consists of integers. They are building a sequence together. In the beginning, the sequence is empty. In one turn a player can remove a number from the left or right side of the array and append it to the sequence. The rule is that the sequence they are building must be strictly increasing. The winner is the player that makes the last move. Alice is playing first. Given the starting array, under the assumption that they both play optimally, who wins the game?
Input
The first line contains one integer N (1 β€ N β€ 2*10^5) - the length of the array A.
The second line contains N integers A_1, A_2,...,A_N (0 β€ A_i β€ 10^9)
Output
The first and only line of output consists of one string, the name of the winner. If Alice won, print "Alice", otherwise, print "Bob".
Examples
Input
1
5
Output
Alice
Input
3
5 4 5
Output
Alice
Input
6
5 8 2 1 10 9
Output
Bob
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from __future__ import division, print_function
import math
import sys
import os
from io import BytesIO, IOBase
#from collections import deque, Counter, OrderedDict, defaultdict
#import heapq
#ceil,floor,log,sqrt,factorial,pow,pi,gcd
#import bisect
#from bisect import bisect_left,bisect_right
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def inp():
return(int(input()))
def inps():
return input().strip()
def inlt():
return(list(map(int,input().split())))
def insr():
s = input().strip()
return(list(s[:len(s)]))
def invr():
return(map(int,input().split()))
n=inp()
l=inlt()
array=0
chnce={'Alice':'Bob','Bob':'Alice'}
strt='Alice'
cntl=1
cntr=1
for i in range(1,n):
if l[i]>l[i-1]:
cntl+=1
else:
break
for i in range(n-2,-1,-1):
if l[i]>l[i+1]:
cntr+=1
else:
break
# print(cntl,cntr)
if cntl%2 or cntr%2:
print(strt)
else:
print(chnce[strt]) | python | code_algorithm | [
{
"input": "6\n5 8 2 1 10 9\n",
"output": "Bob\n"
},
{
"input": "3\n5 4 5\n",
"output": "Alice\n"
},
{
"input": "1\n5\n",
"output": "Alice\n"
},
{
"input": "3\n5 6 5\n",
"output": "Bob\n"
},
{
"input": "2\n5 12\n",
"output": "Alice\n"
}
] | code_contests | python | 0 | 0b82e39a18efc587bc5fec3b4162b3aa |
On the great island of Baltia, there live N people, numbered from 1 to N. There are exactly M pairs of people that are friends with each other. The people of Baltia want to organize a successful party, but they have very strict rules on what a party is and when the party is successful. On the island of Baltia, a party is a gathering of exactly 5 people. The party is considered to be successful if either all the people at the party are friends with each other (so that they can all talk to each other without having to worry about talking to someone they are not friends with) or no two people at the party are friends with each other (so that everyone can just be on their phones without anyone else bothering them). Please help the people of Baltia organize a successful party or tell them that it's impossible to do so.
Input
The first line contains two integer numbers, N (5 β€ N β€ 2*10^5) and M (0 β€ M β€ 2*10^5) β the number of people that live in Baltia, and the number of friendships. The next M lines each contains two integers U_i and V_i (1 β€ U_i,V_i β€ N) β meaning that person U_i is friends with person V_i. Two friends can not be in the list of friends twice (no pairs are repeated) and a person can be friends with themselves (U_i β V_i).
Output
If it's possible to organize a successful party, print 5 numbers indicating which 5 people should be invited to the party. If it's not possible to organize a successful party, print -1 instead. If there are multiple successful parties possible, print any.
Examples
Input
6 3
1 4
4 2
5 4
Output
1 2 3 5 6
Input
5 4
1 2
2 3
3 4
4 5
Output
-1
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
input = sys.stdin.readline
n,m = map(int,input().split())
G = [[] for _ in range(n)]
for _ in range(m):
u,v = map(int,input().split())
u -= 1
v -= 1
if u >= 48 or v >= 48:
continue
G[u].append(v)
G[v].append(u)
if n >= 48:
G = G[:48]
def ok(a,b,c,d,e):
allfd = True
nofd = True
people = [a,b,c,d,e]
for x in people:
for y in people:
if x == y:
continue
if x in G[y]:
nofd = False
else:
allfd = False
return allfd or nofd
sz = len(G)
for a in range(sz):
for b in range(a+1,sz):
for c in range(b+1,sz):
for d in range(c+1,sz):
for e in range(d+1,sz):
if ok(a,b,c,d,e):
ans = [a,b,c,d,e]
print(*[x+1 for x in ans])
exit()
print(-1)
| python | code_algorithm | [
{
"input": "5 4\n1 2\n2 3\n3 4\n4 5\n",
"output": "-1\n"
},
{
"input": "6 3\n1 4\n4 2\n5 4\n",
"output": "1 2 3 5 6\n"
},
{
"input": "6 13\n5 6\n2 5\n1 4\n6 2\n3 5\n4 5\n6 4\n3 1\n1 6\n1 5\n2 4\n6 3\n1 2\n",
"output": "1 2 4 5 6\n"
},
{
"input": "10 8\n5 2\n1 8\n5 7\n1 9\n6 4... | code_contests | python | 0.6 | 190d012411765eb1e1bcac2fefb45fe0 |
Berland State University has received a new update for the operating system. Initially it is installed only on the 1-st computer.
Update files should be copied to all n computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.
Your task is to find the minimum number of hours required to copy the update files to all n computers if there are only k patch cables in Berland State University.
Input
The first line contains a single integer t (1 β€ t β€ 10^5) β the number of test cases.
Each test case consists of a single line that contains two integers n and k (1 β€ k β€ n β€ 10^{18}) β the number of computers and the number of patch cables.
Output
For each test case print one integer β the minimum number of hours required to copy the update files to all n computers.
Example
Input
4
8 3
6 6
7 1
1 1
Output
4
3
6
0
Note
Let's consider the test cases of the example:
* n=8, k=3:
1. during the first hour, we copy the update files from the computer 1 to the computer 2;
2. during the second hour, we copy the update files from the computer 1 to the computer 3, and from the computer 2 to the computer 4;
3. during the third hour, we copy the update files from the computer 1 to the computer 5, from the computer 2 to the computer 6, and from the computer 3 to the computer 7;
4. during the fourth hour, we copy the update files from the computer 2 to the computer 8.
* n=6, k=6:
1. during the first hour, we copy the update files from the computer 1 to the computer 2;
2. during the second hour, we copy the update files from the computer 1 to the computer 3, and from the computer 2 to the computer 4;
3. during the third hour, we copy the update files from the computer 1 to the computer 5, and from the computer 2 to the computer 6.
* n=7, k=1:
1. during the first hour, we copy the update files from the computer 1 to the computer 2;
2. during the second hour, we copy the update files from the computer 1 to the computer 3;
3. during the third hour, we copy the update files from the computer 1 to the computer 4;
4. during the fourth hour, we copy the update files from the computer 4 to the computer 5;
5. during the fifth hour, we copy the update files from the computer 4 to the computer 6;
6. during the sixth hour, we copy the update files from the computer 3 to the computer 7.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
for t in range(int(input())):
n, k = map(int, sys.stdin.readline().strip().split())
ans = 0
cur = 1
while cur <= k and cur < n:
cur *= 2
ans += 1
if cur <= n:
ans += (n - cur + k - 1) // k
print(ans)
| python | code_algorithm | [
{
"input": "4\n8 3\n6 6\n7 1\n1 1\n",
"output": "4\n3\n6\n0\n"
},
{
"input": "1\n576460752303423489 576460752303423489\n",
"output": "60\n"
},
{
"input": "1\n36028797018963968 18014398509481983\n",
"output": "56\n"
},
{
"input": "4\n576460752303423488 288230376151711743\n5764... | code_contests | python | 0 | eaaf5d959fe53391d06797f073326264 |
Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer x with p zeros appended to its end.
Now Monocarp asks you to compare these two numbers. Can you help him?
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of testcases.
The first line of each testcase contains two integers x_1 and p_1 (1 β€ x_1 β€ 10^6; 0 β€ p_1 β€ 10^6) β the description of the first number.
The second line of each testcase contains two integers x_2 and p_2 (1 β€ x_2 β€ 10^6; 0 β€ p_2 β€ 10^6) β the description of the second number.
Output
For each testcase print the result of the comparison of the given two numbers. If the first number is smaller than the second one, print '<'. If the first number is greater than the second one, print '>'. If they are equal, print '='.
Example
Input
5
2 1
19 0
10 2
100 1
1999 0
2 3
1 0
1 0
99 0
1 2
Output
>
=
<
=
<
Note
The comparisons in the example are: 20 > 19, 1000 = 1000, 1999 < 2000, 1 = 1, 99 < 100.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #for line in sys.stdin.readlines()...line = line.strip()
#list(map(int,input().split(" ")))
#list(itertools.permutations([..,..,..]))
#list(itertools.combinations([..,..,..], 3)
import sys
import math
from math import log2 as lg
from collections import deque
import random
import heapq
import itertools
const = 1000000007
n=int(input())
for i in range(n):
first = input().split(" ")
second = input().split(" ")
f,s = len(first[0]) + int(first[1]), len(second[0]) + int(second[1])
if f<s: print("<")
elif f>s: print(">")
else:
found = False
for i in range(min(len(first[0]),len(second[0]))):
if int(first[0][i]) < int(second[0][i]):
print("<")
found = True
break
elif int(first[0][i]) > int(second[0][i]):
print(">")
found = True
break
if not found:
if len(first[0]) > len(second[0]):
if int(first[0][len(second[0]):]) != 0:
print(">")
found = True
elif len(second[0]) > len(first[0]):
if int(second[0][len(first[0]):]) != 0:
print("<")
found = True
if not found: print("=")
| python | code_algorithm | [
{
"input": "5\n2 1\n19 0\n10 2\n100 1\n1999 0\n2 3\n1 0\n1 0\n99 0\n1 2\n",
"output": ">\n=\n<\n=\n<\n"
},
{
"input": "1\n2000 0\n2 3\n",
"output": "=\n"
},
{
"input": "1\n1 6\n1000000 0\n",
"output": "=\n"
},
{
"input": "3\n1 3\n100 1\n2 3\n200 1\n6 3\n600 1\n",
"output"... | code_contests | python | 0.7 | e2bf854e57e1f6db0f88220b81e7c86d |
You are given a sequence a_1, a_2, ..., a_n consisting of n pairwise distinct positive integers.
Find \leftβ \frac n 2 \rightβ different pairs of integers x and y such that:
* x β y;
* x and y appear in a;
* x~mod~y doesn't appear in a.
Note that some x or y can belong to multiple pairs.
β x β denotes the floor function β the largest integer less than or equal to x. x~mod~y denotes the remainder from dividing x by y.
If there are multiple solutions, print any of them. It can be shown that at least one solution always exists.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of testcases.
The first line of each testcase contains a single integer n (2 β€ n β€ 2 β
10^5) β the length of the sequence.
The second line of each testcase contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^6).
All numbers in the sequence are pairwise distinct. The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
The answer for each testcase should contain \leftβ \frac n 2 \rightβ different pairs of integers x and y such that x β y, x and y appear in a and x~mod~y doesn't appear in a. Print the pairs one after another.
You can print the pairs in any order. However, the order of numbers in the pair should be exactly such that the first number is x and the second number is y. All pairs should be pairwise distinct.
If there are multiple solutions, print any of them.
Example
Input
4
2
1 4
4
2 8 3 4
5
3 8 5 9 7
6
2 7 5 3 4 8
Output
4 1
8 2
8 4
9 5
7 5
8 7
4 3
5 2
Note
In the first testcase there are only two pairs: (1, 4) and (4, 1). \leftβ \frac 2 2 \rightβ=1, so we have to find one pair. 1~mod~4=1, and 1 appears in a, so that pair is invalid. Thus, the only possible answer is a pair (4, 1).
In the second testcase, we chose pairs 8~mod~2=0 and 8~mod~4=0. 0 doesn't appear in a, so that answer is valid. There are multiple possible answers for that testcase.
In the third testcase, the chosen pairs are 9~mod~5=4 and 7~mod~5=2. Neither 4, nor 2, appears in a, so that answer is valid.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | for _ in range(int(input())):
n=int(input())
a=list(map(int, input().split()))
a.sort()
y=a[0]
for i in range(1,n//2 + 1):
print(a[i] , y)
| python | code_algorithm | [
{
"input": "4\n2\n1 4\n4\n2 8 3 4\n5\n3 8 5 9 7\n6\n2 7 5 3 4 8\n",
"output": "4 1\n3 2\n4 2\n5 3\n7 3\n3 2\n4 2\n5 2\n"
},
{
"input": "1\n5\n200005 200006 200007 200008 200009\n",
"output": "200006 200005\n200007 200005\n"
},
{
"input": "1\n2\n4 2\n",
"output": "4 2\n"
},
{
... | code_contests | python | 0 | 7a181447fbe88b957d382a337e51b4a8 |
Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts 100^{500} seconds, during which Monocarp attacks the dragon with a poisoned dagger. The i-th attack is performed at the beginning of the a_i-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals 1 damage during each of the next k seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).
For example, suppose k = 4, and Monocarp stabs the dragon during the seconds 2, 4 and 10. Then the poison effect is applied at the start of the 2-nd second and deals 1 damage during the 2-nd and 3-rd seconds; then, at the beginning of the 4-th second, the poison effect is reapplied, so it deals exactly 1 damage during the seconds 4, 5, 6 and 7; then, during the 10-th second, the poison effect is applied again, and it deals 1 damage during the seconds 10, 11, 12 and 13. In total, the dragon receives 10 damage.
Monocarp knows that the dragon has h hit points, and if he deals at least h damage to the dragon during the battle β he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of k (the number of seconds the poison effect lasts) that is enough to deal at least h damage to the dragon.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of the test case contains two integers n and h (1 β€ n β€ 100; 1 β€ h β€ 10^{18}) β the number of Monocarp's attacks and the amount of damage that needs to be dealt.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9; a_i < a_{i + 1}), where a_i is the second when the i-th attack is performed.
Output
For each test case, print a single integer β the minimum value of the parameter k, such that Monocarp will cause at least h damage to the dragon.
Example
Input
4
2 5
1 5
3 10
2 4 10
5 3
1 2 4 5 7
4 1000
3 25 64 1337
Output
3
4
1
470
Note
In the first example, for k=3, damage is dealt in seconds [1, 2, 3, 5, 6, 7].
In the second example, for k=4, damage is dealt in seconds [2, 3, 4, 5, 6, 7, 10, 11, 12, 13].
In the third example, for k=1, damage is dealt in seconds [1, 2, 4, 5, 7].
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
#s = input()
#n= (map(int, input().split()))
#(map(int, input().split()))
#a, b = (map(int, input().split()))
for i in range(0, int(input())):
n, h =(map(int, input().split()))
a = list(map(int, input().split()))
dist = list()
for j in range(0, len(a)-1):
dist.append(a[j+1]-a[j])
dist.sort()
if(len(dist)==0):
dist.append(a[0])
else:
dist.append(dist[len(dist)-1])
sum = 0
pred_sum = 0
flag = 0
k = 0
for j in range(0, len(a)):
sum = pred_sum+(len(a)-j)*dist[j]
if(sum>=h):
flag = 1
k = j
break
pred_sum += dist[j]
if(flag == 0):
if(len(dist)==1):
print(h)
else:
print(h-pred_sum+dist[len(dist)-1])
else:
sum = 0
sum = (h-pred_sum)//(len(a)-k)
if((h-pred_sum)%(len(a)-k)):
sum += 1
print(sum)
| python | code_algorithm | [
{
"input": "4\n2 5\n1 5\n3 10\n2 4 10\n5 3\n1 2 4 5 7\n4 1000\n3 25 64 1337\n",
"output": "3\n4\n1\n470\n"
},
{
"input": "1\n2 1000000000000000000\n1 1000000000\n",
"output": "999999999000000001\n"
},
{
"input": "1\n2 1000000000000000000\n1000000 1000000000\n",
"output": "99999999900... | code_contests | python | 0 | c9f6ae263bdc8682251c0d4c7108f19a |
You are given an array a of n integers, and another integer k such that 2k β€ n.
You have to perform exactly k operations with this array. In one operation, you have to choose two elements of the array (let them be a_i and a_j; they can be equal or different, but their positions in the array must not be the same), remove them from the array, and add β (a_i)/(a_j) β to your score, where β x/y β is the maximum integer not exceeding x/y.
Initially, your score is 0. After you perform exactly k operations, you add all the remaining elements of the array to the score.
Calculate the minimum possible score you can get.
Input
The first line of the input contains one integer t (1 β€ t β€ 500) β the number of test cases.
Each test case consists of two lines. The first line contains two integers n and k (1 β€ n β€ 100; 0 β€ k β€ β n/2 β).
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5).
Output
Print one integer β the minimum possible score you can get.
Example
Input
5
7 3
1 1 1 2 1 3 1
5 1
5 5 5 5 5
4 2
1 3 3 7
2 0
4 2
9 2
1 10 10 1 10 2 7 10 3
Output
2
16
0
6
16
Note
Let's consider the example test.
In the first test case, one way to obtain a score of 2 is the following one:
1. choose a_7 = 1 and a_4 = 2 for the operation; the score becomes 0 + β 1/2 β = 0, the array becomes [1, 1, 1, 1, 3];
2. choose a_1 = 1 and a_5 = 3 for the operation; the score becomes 0 + β 1/3 β = 0, the array becomes [1, 1, 1];
3. choose a_1 = 1 and a_2 = 1 for the operation; the score becomes 0 + β 1/1 β = 1, the array becomes [1];
4. add the remaining element 1 to the score, so the resulting score is 2.
In the second test case, no matter which operations you choose, the resulting score is 16.
In the third test case, one way to obtain a score of 0 is the following one:
1. choose a_1 = 1 and a_2 = 3 for the operation; the score becomes 0 + β 1/3 β = 0, the array becomes [3, 7];
2. choose a_1 = 3 and a_2 = 7 for the operation; the score becomes 0 + β 3/7 β = 0, the array becomes empty;
3. the array is empty, so the score doesn't change anymore.
In the fourth test case, no operations can be performed, so the score is the sum of the elements of the array: 4 + 2 = 6.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
import os
import sys
from io import BytesIO, IOBase
M = 1000000007
import random
import heapq
import threading
import bisect
import time
#sys.setrecursionlimit(2*(10**5))
from functools import *
from collections import *
from itertools import *
BUFSIZE = 8192
import array
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):
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 build(a,b,st,arr,node):
if a==b:
st[node] = arr[a]
return arr[a]
mid = (a+b)//2
p = build(a,mid,st,arr,2*node+1)
q = build(mid+1,b,st,arr,2*node+2)
st[node] = p+q
return st[node]
def update(st,a,b,x,val,node):
if x<a or x>b:
return
st[node] = st[node] + val
if a!=b:
mid = (a+b)//2
update(st,a,mid,x,val,2*node+1)
update(st,mid+1,b,x,val,2*node+2)
def getsum(st,a,b,l,r,node):
if l>b or r<a:
return 0
if l<=a and r>=b:
return st[node]
mid = (a+b)//2
return getsum(st,a,mid,l,r,2*node+1) + getsum(st,mid+1,b,l,r,2*node+2)
def dfs2(curr,parent,start,end,cnt,res,d,arr):
res[cnt[0]] = arr[curr-1]
start[curr] = cnt[0]
cnt[0]+=1
for i in d[curr]:
if i!=parent:
dfs2(i,curr,start,end,cnt,res,d,arr)
cnt[0]+=1
res[cnt[0]] = arr[curr-1]
end[curr] = cnt[0]
"""-------------------Subtree queries problem on cses
def main():
t = 1
#t = inpu()
for _ in range(t):
n,q = sep()
arr = lis()
d = defaultdict(list)
for i in range(n-1):
a,b = sep()
d[a].append(b)
d[b].append(a)
res = [0]*(2*n)
start = defaultdict(int)
end = defaultdict(int)
cnt = [0]
dfs2(1,-1,start,end,cnt,res,d,arr)
print(res)
st=[0]*(4*(len(res)))
build(0,len(res)-1,st,res,0)
#print(st)
for i in range(q):
l = lis()
if l[0]==1:
p,q = start[l[1]],end[l[1]]
diff = l[2] - res[p]
res[p] = l[2]
diff2 = l[2] - res[q]
res[q] = l[2]
update(st,0,len(res)-1,p,diff,0)
update(st,0,len(res)-1,q,diff2,0)
else:
p,q = start[l[1]],end[l[1]]
print(getsum(st,0,len(res)-1,p,q,0)//2)
"""
"""def build2(a,b,st,arr,node,s):
if a==b:
s.add(arr[a-1])
st[node] = len(s)
return s
mid = (a+b)//2
p = build2(a,mid,st,arr,2*node+1,s)
q = build2(mid+1,b,st,arr,2*node+2,s)
#print(p,q)
p.union(q)
st[node] = len(p)
return p
def ans(a,b,st,l,r,node):
if l>b or r<a:
return 0
if l<=a and r>=b:
return st[node]
mid=(a+b)//2
return ans(a,mid,st,l,r,2*node+1)+ans(mid+1,b,st,l,r,2*node+2)"""
def main():
t=1
t=inpu()
for _ in range(t):
n,k = sep()
arr = lis()
arr.sort()
ans = sum(arr[:n-2*k])
p = arr[n-2*k:]
c = Counter(p)
max1 = 0
for i in c:
max1 = max(max1,c[i])
res = max(0,(2*max1-2*k)//2)
print(ans+res)
if __name__ == '__main__':
"""
threading.stack_size(2 * 10 ** 8)
threading.Thread(target=main).start()
"""
main()
| python | code_algorithm | [
{
"input": "5\n7 3\n1 1 1 2 1 3 1\n5 1\n5 5 5 5 5\n4 2\n1 3 3 7\n2 0\n4 2\n9 2\n1 10 10 1 10 2 7 10 3\n",
"output": "2\n16\n0\n6\n16\n"
},
{
"input": "1\n6 3\n4 4 5 5 6 6\n",
"output": "0\n"
},
{
"input": "1\n6 3\n1 1 1 1 2 2\n",
"output": "1\n"
},
{
"input": "1\n9 3\n1 1 1 2... | code_contests | python | 0 | c843f5a976f762c8c026a79e8501c443 |
You are given two positive integers x and y. You can perform the following operation with x: write it in its binary form without leading zeros, add 0 or 1 to the right of it, reverse the binary form and turn it into a decimal number which is assigned as the new value of x.
For example:
* 34 can be turned into 81 via one operation: the binary form of 34 is 100010, if you add 1, reverse it and remove leading zeros, you will get 1010001, which is the binary form of 81.
* 34 can be turned into 17 via one operation: the binary form of 34 is 100010, if you add 0, reverse it and remove leading zeros, you will get 10001, which is the binary form of 17.
* 81 can be turned into 69 via one operation: the binary form of 81 is 1010001, if you add 0, reverse it and remove leading zeros, you will get 1000101, which is the binary form of 69.
* 34 can be turned into 69 via two operations: first you turn 34 into 81 and then 81 into 69.
Your task is to find out whether x can be turned into y after a certain number of operations (possibly zero).
Input
The only line of the input contains two integers x and y (1 β€ x, y β€ 10^{18}).
Output
Print YES if you can make x equal to y and NO if you can't.
Examples
Input
3 3
Output
YES
Input
7 4
Output
NO
Input
2 8
Output
NO
Input
34 69
Output
YES
Input
8935891487501725 71487131900013807
Output
YES
Note
In the first example, you don't even need to do anything.
The fourth example is described in the statement.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #import io,os
#input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
def main(t):
x, y = map(int,input().split())
sx, sy = bin(x)[2:],bin(y)[2:]
dic = {}
queue = deque()
queue.append(sx)
dic[sx] = 1
i = len(sx)-1
while i>=0 and sx[i]=='0': i -= 1
queue.append(sx[:i+1])
dic[sx[:i+1]] = 1
# print(dic)
while queue:
curr = queue.popleft()
nextcurr1 = curr[::-1]
i = 0
while nextcurr1[i]=='0': i += 1
nextcurr1 = nextcurr1[i:]
if nextcurr1 not in dic:
dic[nextcurr1] = 1
queue.append(nextcurr1)
nextcurr2 = (curr + '1')[::-1]
if nextcurr2 not in dic:
dic[nextcurr2] = 1
if len(nextcurr2) <= len(sy): queue.append(nextcurr2)
# print(dic)
if sy in dic:
print("YES")
else:
print("NO")
T = 1 #int(input())
t = 1
while t<=T:
main(t)
t += 1
| python | code_algorithm | [
{
"input": "2 8\n",
"output": "NO\n"
},
{
"input": "7 4\n",
"output": "NO\n"
},
{
"input": "8935891487501725 71487131900013807\n",
"output": "YES\n"
},
{
"input": "3 3\n",
"output": "YES\n"
},
{
"input": "34 69\n",
"output": "YES\n"
},
{
"input": "4700... | code_contests | python | 0 | ee919416f7547b59f73998f57b6dcd6e |
Polycarp likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: 1, 4, 8, 9, ....
For a given number n, count the number of integers from 1 to n that Polycarp likes. In other words, find the number of such x that x is a square of a positive integer number or a cube of a positive integer number (or both a square and a cube simultaneously).
Input
The first line contains an integer t (1 β€ t β€ 20) β the number of test cases.
Then t lines contain the test cases, one per line. Each of the lines contains one integer n (1 β€ n β€ 10^9).
Output
For each test case, print the answer you are looking for β the number of integers from 1 to n that Polycarp likes.
Example
Input
6
10
1
25
1000000000
999999999
500000000
Output
4
1
6
32591
32590
23125
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` |
for i in range(int(input())):
n=int(input())
count=[0]
if n==1:
print(1)
else:
for i in range(1,n):
if i*i>n:
break
if i*i<=n:
count.append(i*i)
if i*i*i<=n:
count.append(i*i*i)
else:
pass
print(len(set(count))-1)
| python | code_algorithm | [
{
"input": "6\n10\n1\n25\n1000000000\n999999999\n500000000\n",
"output": "4\n1\n6\n32591\n32590\n23125\n"
},
{
"input": "2\n64\n15625\n",
"output": "10\n145\n"
},
{
"input": "8\n64000000\n85766121\n113379904\n148035889\n191102976\n244140625\n594823321\n887503681\n",
"output": "8380\n... | code_contests | python | 0 | 6c9f898ead11fb33b5717e51cc446587 |
You are given a permutation p of n elements. A permutation of n elements is an array of length n containing each integer from 1 to n exactly once. For example, [1, 2, 3] and [4, 3, 5, 1, 2] are permutations, but [1, 2, 4] and [4, 3, 2, 1, 2] are not permutations. You should perform q queries.
There are two types of queries:
* 1 x y β swap p_x and p_y.
* 2 i k β print the number that i will become if we assign i = p_i k times.
Input
The first line contains two integers n and q (1 β€ n, q β€ 10^5).
The second line contains n integers p_1, p_2, ..., p_n.
Each of the next q lines contains three integers. The first integer is t (1 β€ t β€ 2) β type of query. If t = 1, then the next two integers are x and y (1 β€ x, y β€ n; x β y) β first-type query. If t = 2, then the next two integers are i and k (1 β€ i, k β€ n) β second-type query.
It is guaranteed that there is at least one second-type query.
Output
For every second-type query, print one integer in a new line β answer to this query.
Examples
Input
5 4
5 3 4 2 1
2 3 1
2 1 2
1 1 3
2 1 2
Output
4
1
2
Input
5 9
2 3 5 1 4
2 3 5
2 5 5
2 5 1
2 5 3
2 5 4
1 5 4
2 5 3
2 2 5
2 5 1
Output
3
5
4
2
3
3
3
1
Note
In the first example p = \{5, 3, 4, 2, 1\}.
The first query is to print p_3. The answer is 4.
The second query is to print p_{p_1}. The answer is 1.
The third query is to swap p_1 and p_3. Now p = \{4, 3, 5, 2, 1\}.
The fourth query is to print p_{p_1}. The answer is 2.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` |
def main():
n, q = readIntArr()
p = readIntArr()
for i in range(n):
p[i] -= 1 # make 0-index
base = int(n ** 0.5 + 1)
a = [-1] * n # a[i] is i after base operations
r = [-1] * n # r is reverse of p, i.e. base operations back. r[p[i]] = i
for i in range(n):
r[p[i]] = i
i2 = i
for _ in range(base):
i = p[i]
a[i2] = i
allans = []
# print('initial p:{} r:{} a:{} base:{}'.format(p, r, a, base))
for _ in range(q):
t, x, y = readIntArr()
if t == 1: # swap
x -= 1; y -= 1
temp = p[x]; p[x] = p[y]; p[y] = temp
# update the reverse
r[p[x]] = x; r[p[y]] = y
# print('x:{} y:{} p:{} r:{} a:{}'.format(x, y, p, r, a))
# re-run computation
for z in (x, y): # re-compute base items back in O(base) time
for __ in range(base + 1):
z = r[z]
j = i = z
for __ in range(base):
j = p[j]
for __ in range(base + 2):
# print('i:{} j:{}'.format(i, j))
a[i] = j
i = p[i]
j = p[j]
else:
i = x; k = y
i -= 1
while k >= base:
i = a[i]
k -= base
while k >= 1:
i = p[i]
k -= 1
allans.append(i + 1) # 1-index answer
multiLineArrayPrint(allans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a, b, c):
print('? {} {} {}'.format(a, b, c))
sys.stdout.flush()
return int(input())
def answerInteractive(ansArr):
print('! {}'.format(' '.join([str(x) for x in ansArr])))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2
for _abc in range(1):
main() | python | code_algorithm | [
{
"input": "5 9\n2 3 5 1 4\n2 3 5\n2 5 5\n2 5 1\n2 5 3\n2 5 4\n1 5 4\n2 5 3\n2 2 5\n2 5 1\n",
"output": "3\n5\n4\n2\n3\n3\n3\n1\n"
},
{
"input": "5 4\n5 3 4 2 1\n2 3 1\n2 1 2\n1 1 3\n2 1 2\n",
"output": "4\n1\n2\n"
},
{
"input": "1 1\n1\n2 1 1\n",
"output": "1\n"
},
{
"input"... | code_contests | python | 0.8 | e8a840ec24cea991b3b6d2646ecca5d8 |
You had n positive integers a_1, a_2, ..., a_n arranged in a circle. For each pair of neighboring numbers (a_1 and a_2, a_2 and a_3, ..., a_{n - 1} and a_n, and a_n and a_1), you wrote down: are the numbers in the pair equal or not.
Unfortunately, you've lost a piece of paper with the array a. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array a which is consistent with information you have about equality or non-equality of corresponding pairs?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases. Next t cases follow.
The first and only line of each test case contains a non-empty string s consisting of characters E and/or N. The length of s is equal to the size of array n and 2 β€ n β€ 50. For each i from 1 to n:
* if s_i = E then a_i is equal to a_{i + 1} (a_n = a_1 for i = n);
* if s_i = N then a_i is not equal to a_{i + 1} (a_n β a_1 for i = n).
Output
For each test case, print YES if it's possible to choose array a that are consistent with information from s you know. Otherwise, print NO.
It can be proved, that if there exists some array a, then there exists an array a of positive integers with values less or equal to 10^9.
Example
Input
4
EEE
EN
ENNEENE
NENN
Output
YES
NO
YES
YES
Note
In the first test case, you can choose, for example, a_1 = a_2 = a_3 = 5.
In the second test case, there is no array a, since, according to s_1, a_1 is equal to a_2, but, according to s_2, a_2 is not equal to a_1.
In the third test case, you can, for example, choose array a = [20, 20, 4, 50, 50, 50, 20].
In the fourth test case, you can, for example, choose a = [1, 3, 3, 7].
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from itertools import permutations as per
from math import factorial as fact
from difflib import SequenceMatcher
t = int(input())
# map(int,input().split())
# [int(i) for i in input().split()]
for _ in range(t):
s = input()
print("YES") if s.count('N') != 1 else print("NO") | python | code_algorithm | [
{
"input": "4\nEEE\nEN\nENNEENE\nNENN\n",
"output": "YES\nNO\nYES\nYES\n"
},
{
"input": "1\nNEEEEEEEEEEEEEEEEEEEEEEEEEEEEENNNNEENNE\n",
"output": "YES\n"
},
{
"input": "2\nEEEEEEN\nEEEEEEEN\n",
"output": "NO\nNO\n"
},
{
"input": "2\nEEEEEN\nEEEEEN\n",
"output": "NO\nNO\n"... | code_contests | python | 0 | b2054af6a0a54119a2c0860d5993b939 |
There are three sticks with integer lengths l_1, l_2 and l_3.
You are asked to break exactly one of them into two pieces in such a way that:
* both pieces have positive (strictly greater than 0) integer length;
* the total length of the pieces is equal to the original length of the stick;
* it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides.
A square is also considered a rectangle.
Determine if it's possible to do that.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of testcases.
The only line of each testcase contains three integers l_1, l_2, l_3 (1 β€ l_i β€ 10^8) β the lengths of the sticks.
Output
For each testcase, print "YES" if it's possible to break one of the sticks into two pieces with positive integer length in such a way that it's possible to construct a rectangle from the resulting four sticks. Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as a positive answer).
Example
Input
4
6 1 5
2 5 2
2 4 2
5 5 4
Output
YES
NO
YES
YES
Note
In the first testcase, the first stick can be broken into parts of length 1 and 5. We can construct a rectangle with opposite sides of length 1 and 5.
In the second testcase, breaking the stick of length 2 can only result in sticks of lengths 1, 1, 2, 5, which can't be made into a rectangle. Breaking the stick of length 5 can produce results 2, 3 or 1, 4 but neither of them can't be put into a rectangle.
In the third testcase, the second stick can be broken into parts of length 2 and 2. The resulting rectangle has opposite sides 2 and 2 (which is a square).
In the fourth testcase, the third stick can be broken into parts of length 2 and 2. The resulting rectangle has opposite sides 2 and 5.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | for _ in range(int(input())):
a, b, c = map(int, input().split())
if a == b + c or b == a + c or c == a + b:
print('YES')
elif a == b and c % 2 == 0:
print('YES')
elif a == c and b % 2 == 0:
print('YES')
elif b == c and a % 2 == 0:
print('YES')
else:
print('NO')
| python | code_algorithm | [
{
"input": "4\n6 1 5\n2 5 2\n2 4 2\n5 5 4\n",
"output": "YES\nNO\nYES\nYES\n"
},
{
"input": "2\n1 2 3\n2 2 4\n",
"output": "YES\nYES\n"
},
{
"input": "1\n1 98 99\n",
"output": "YES\n"
},
{
"input": "3\n1 1 1\n2 1 3\n5 6 7\n",
"output": "NO\nYES\nNO\n"
},
{
"input"... | code_contests | python | 0.1 | 2879205d306123ae9ce4dbcf776f3007 |
You are given an integer array a_1, a_2, ..., a_n and integer k.
In one step you can
* either choose some index i and decrease a_i by one (make a_i = a_i - 1);
* or choose two indices i and j and set a_i equal to a_j (make a_i = a_j).
What is the minimum number of steps you need to make the sum of array β_{i=1}^{n}{a_i} β€ k? (You are allowed to make values of array negative).
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 10^{15}) β the size of array a and upper bound on its sum.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the array itself.
It's guaranteed that the sum of n over all test cases doesn't exceed 2 β
10^5.
Output
For each test case, print one integer β the minimum number of steps to make β_{i=1}^{n}{a_i} β€ k.
Example
Input
4
1 10
20
2 69
6 9
7 8
1 2 1 3 1 2 1
10 1
1 2 3 1 2 6 1 6 8 10
Output
10
0
2
7
Note
In the first test case, you should decrease a_1 10 times to get the sum lower or equal to k = 10.
In the second test case, the sum of array a is already less or equal to 69, so you don't need to change it.
In the third test case, you can, for example:
1. set a_4 = a_3 = 1;
2. decrease a_4 by one, and get a_4 = 0.
As a result, you'll get array [1, 2, 1, 0, 1, 2, 1] with sum less or equal to 8 in 1 + 1 = 2 steps.
In the fourth test case, you can, for example:
1. choose a_7 and decrease in by one 3 times; you'll get a_7 = -2;
2. choose 4 elements a_6, a_8, a_9 and a_{10} and them equal to a_7 = -2.
As a result, you'll get array [1, 2, 3, 1, 2, -2, -2, -2, -2, -2] with sum less or equal to 1 in 3 + 4 = 7 steps.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
import os.path
from collections import *
import math
import bisect
import heapq as hq
from fractions import Fraction
from random import randint
if os.path.exists("input.txt"):
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
input = sys.stdin.readline
##########################################################
def solve():
n,k = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
x = sum(arr)
if(sum(arr) <= k):
print(0)
return
arr.sort()
pos = 0
Sum = 0
res = 1e16
while pos < n:
Sum += arr[pos]
x = (Sum - arr[0])
# print(x)
x = k - x
y = n - pos
z = min(x // y, arr[0])
# print(Sum,x,y,z)
res = min(res, arr[0] - z + y - 1)
pos += 1
print(res)
t = int(input())
while t:
t -= 1
solve()
##########################################################
| python | code_algorithm | [
{
"input": "4\n1 10\n20\n2 69\n6 9\n7 8\n1 2 1 3 1 2 1\n10 1\n1 2 3 1 2 6 1 6 8 10\n",
"output": "10\n0\n2\n7\n"
},
{
"input": "1\n84 781\n403 867 729 928 240 410 849 95 651 852 230 209 358 596 576 230 924 448 288 19 680 470 839 107 931 809 347 903 399 185 840 326 338 758 584 385 862 140 256 537 677... | code_contests | python | 0 | dca475f9b068aea1d370ddd66b3407af |
You are given a binary string (i. e. a string consisting of characters 0 and/or 1) s of length n. You can perform the following operation with the string s at most once: choose a substring (a contiguous subsequence) of s having exactly k characters 1 in it, and shuffle it (reorder the characters in the substring as you wish).
Calculate the number of different strings which can be obtained from s by performing this operation at most once.
Input
The first line contains two integers n and k (2 β€ n β€ 5000; 0 β€ k β€ n).
The second line contains the string s of length n, consisting of characters 0 and/or 1.
Output
Print one integer β the number of different strings which can be obtained from s by performing the described operation at most once. Since the answer can be large, output it modulo 998244353.
Examples
Input
7 2
1100110
Output
16
Input
5 0
10010
Output
1
Input
8 1
10001000
Output
10
Input
10 8
0010011000
Output
1
Note
Some strings you can obtain in the first example:
* to obtain 0110110, you can take the substring from the 1-st character to the 4-th character, which is 1100, and reorder its characters to get 0110;
* to obtain 1111000, you can take the substring from the 3-rd character to the 7-th character, which is 00110, and reorder its characters to get 11000;
* to obtain 1100101, you can take the substring from the 5-th character to the 7-th character, which is 110, and reorder its characters to get 101.
In the second example, k = 0 so you can only choose the substrings consisting only of 0 characters. Reordering them doesn't change the string at all, so the only string you can obtain is 10010.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import stdin, stdout
N = 998244353
def egcd(a, b):
"""return (g, x, y) such that a*x + b*y = g = gcd(a, b)"""
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m = N):
"""return inverse of a mod m"""
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
fact = [1]
invfact = [1]
for i in range(1,5001):
fact.append((fact[-1]*i)%N)
invfact.append((invfact[-1]*modinv(i))%N)
n, k = [int(x) for x in stdin.readline().split()]
s = stdin.readline().strip()
locations = []
for i in range(n):
if s[i] == '1':
locations.append(i)
if k == 0 or len(locations) < k:
stdout.write('1\n')
else:
answer = 0
for i in range(len(locations)-k+1):
if i == 0:
lower = 0
else:
lower = locations[i-1]+1
if i == len(locations)-k:
upper = n-1
else:
upper = locations[i+k]-1
answer = (answer + fact[upper-lower+1]*invfact[k]*invfact[upper-lower+1-k])%N
for i in range(len(locations)-k):
lower = locations[i]+1
upper = locations[i+k]-1
answer = (answer - fact[upper-lower+1]*invfact[k-1]*invfact[upper-lower+1-k+1])%N
stdout.write(str(answer)+'\n')
| python | code_algorithm | [
{
"input": "10 8\n0010011000\n",
"output": "1\n"
},
{
"input": "5 0\n10010\n",
"output": "1\n"
},
{
"input": "8 1\n10001000\n",
"output": "10\n"
},
{
"input": "7 2\n1100110\n",
"output": "16\n"
},
{
"input": "5 2\n00011\n",
"output": "10\n"
},
{
"input... | code_contests | python | 0 | 0921790b4d1ff3f65f38259f2a60ad25 |
The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.
A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are numbered from 1 to n from top to bottom, and columns of the floor are numbered from 1 to m from left to right. The cell on the intersection of the r-th row and the c-th column is denoted as (r,c). The initial position of the robot is (r_b, c_b).
In one second, the robot moves by dr rows and dc columns, that is, after one second, the robot moves from the cell (r, c) to (r + dr, c + dc). Initially dr = 1, dc = 1. If there is a vertical wall (the left or the right walls) in the movement direction, dc is reflected before the movement, so the new value of dc is -dc. And if there is a horizontal wall (the upper or lower walls), dr is reflected before the movement, so the new value of dr is -dr.
Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at (r_d, c_d). The job of the robot is to clean that dirty cell.
After a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability \frac p {100} only, and not performed with probability 1 - \frac p {100}. The cleaning or not cleaning outcomes are independent each second.
Given the floor size n and m, the robot's initial position (r_b, c_b) and the dirty cell's position (r_d, c_d), find the expected time for the robot to do its job.
It can be shown that the answer can be expressed as an irreducible fraction \frac x y, where x and y are integers and y not β‘ 0 \pmod{10^9 + 7} . Output the integer equal to x β
y^{-1} mod (10^9 + 7). In other words, output such an integer a that 0 β€ a < 10^9 + 7 and a β
y β‘ x \pmod {10^9 + 7}.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10). Description of the test cases follows.
A test case consists of only one line, containing n, m, r_b, c_b, r_d, c_d, and p (4 β€ n β
m β€ 10^5, n, m β₯ 2, 1 β€ r_b, r_d β€ n, 1 β€ c_b, c_d β€ m, 1 β€ p β€ 99) β the sizes of the room, the initial position of the robot, the position of the dirt cell and the probability of cleaning in percentage.
Output
For each test case, print a single integer β the expected time for the robot to clean the dirty cell, modulo 10^9 + 7.
Example
Input
6
2 2 1 1 2 1 25
3 3 1 2 2 2 25
10 10 1 1 10 10 75
10 10 10 10 1 1 75
5 5 1 3 2 2 10
97 98 3 5 41 43 50
Output
3
3
15
15
332103349
99224487
Note
In the first test case, the robot has the opportunity to clean the dirty cell every second. Using the [geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution), we can find out that with the success rate of 25\%, the expected number of tries to clear the dirty cell is \frac 1 {0.25} = 4. But because the first moment the robot has the opportunity to clean the cell is before the robot starts moving, the answer is 3.
<image> Illustration for the first example. The blue arc is the robot. The red star is the target dirt cell. The purple square is the initial position of the robot. Each second the robot has an opportunity to clean a row and a column, denoted by yellow stripes.
In the second test case, the board size and the position are different, but the robot still has the opportunity to clean the dirty cell every second, and it has the same probability of cleaning. Therefore the answer is the same as in the first example.
<image> Illustration for the second example.
The third and the fourth case are almost the same. The only difference is that the position of the dirty cell and the robot are swapped. But the movements in both cases are identical, hence the same result.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
from sys import stdin
import math
mod = 10**9+7
def inverse(n,mod):
return pow(n,mod-2,mod)
onehand = inverse(100,mod)
tt = int(stdin.readline())
ANS = []
for _ in range(tt):
n,m,rb,cb,rd,cd,p = map(int,stdin.readline().split())
p = p*onehand % mod
#print (p)
loop = 2*(n-1)*2*(m-1) // math.gcd( 2*(n-1) , 2*(m-1) )
xmods = []
tx = rb
diffx = 1 if n != 1 else 0
for i in range(loop):
if tx == rd:
xmods.append( i )
if not ( 1 <= tx+diffx <= n ):
diffx *= -1
tx += diffx
ymods = []
ty = cb
diffy = 1 if m != 1 else 0
for i in range(loop):
if ty == cd:
ymods.append( i )
if not ( 1 <= ty+diffy <= m ):
diffy *= -1
ty += diffy
s = set(xmods)
for i in ymods:
s.add(i)
lis = list(s)
lis.sort()
#print (lis,loop)
lasta,lastb = 0,1
for i in range(len(lis)-1,-1,-1):
if i == len(lis)-1:
kai = loop - lis[i]
else:
kai = lis[i+1] - lis[i]
newa = ( (1-p)*(lasta+kai) ) % mod
newb = ( (1-p)*lastb ) % mod
#print (lis[i] , newa , newb , kai )
if i == 0:
ans = (newa+lis[0]) *inverse(1-newb,mod)
ANS.append( str( ans % mod ) )
lasta,lastb = newa,newb
#print ("\n".join(ANS))
print ("\n".join(ANS)) | python | code_algorithm | [
{
"input": "6\n2 2 1 1 2 1 25\n3 3 1 2 2 2 25\n10 10 1 1 10 10 75\n10 10 10 10 1 1 75\n5 5 1 3 2 2 10\n97 98 3 5 41 43 50\n",
"output": "3\n3\n15\n15\n332103349\n99224487\n"
},
{
"input": "10\n8 5279 1 1543 6 1521 6\n25276 2 25276 2 1365 1 36\n49526 2 1 1 9796 2 29\n374 73 225 73 291 27 26\n4786 11 ... | code_contests | python | 0 | b2718767b99e2fd1d164651d564eb67d |
There are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.
We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold:
* Either this person does not go on the trip,
* Or at least k of his friends also go on the trip.
Note that the friendship is not transitive. That is, if a and b are friends and b and c are friends, it does not necessarily imply that a and c are friends.
For each day, find the maximum number of people that can go on the trip on that day.
Input
The first line contains three integers n, m, and k (2 β€ n β€ 2 β
10^5, 1 β€ m β€ 2 β
10^5, 1 β€ k < n) β the number of people, the number of days and the number of friends each person on the trip should have in the group.
The i-th (1 β€ i β€ m) of the next m lines contains two integers x and y (1β€ x, yβ€ n, xβ y), meaning that persons x and y become friends on the morning of day i. It is guaranteed that x and y were not friends before.
Output
Print exactly m lines, where the i-th of them (1β€ iβ€ m) contains the maximum number of people that can go on the trip on the evening of the day i.
Examples
Input
4 4 2
2 3
1 2
1 3
1 4
Output
0
0
3
3
Input
5 8 2
2 1
4 2
5 4
5 2
4 3
5 1
4 1
3 2
Output
0
0
0
3
3
4
4
5
Input
5 7 2
1 5
3 2
2 5
3 4
1 2
5 3
1 3
Output
0
0
0
0
3
4
4
Note
In the first example,
* 1,2,3 can go on day 3 and 4.
In the second example,
* 2,4,5 can go on day 4 and 5.
* 1,2,4,5 can go on day 6 and 7.
* 1,2,3,4,5 can go on day 8.
In the third example,
* 1,2,5 can go on day 5.
* 1,2,3,5 can go on day 6 and 7.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from collections import deque
def solve(adj, m, k, uv):
n = len(adj)
nn = [len(a) for a in adj]
q = deque()
for i in range(n):
if nn[i] < k:
q.append(i)
while q:
v = q.popleft()
for u in adj[v]:
nn[u] -= 1
if nn[u] == k-1:
q.append(u)
res = [0]*m
nk = len([1 for i in nn if i >= k])
res[-1] = nk
for i in range(m-1, 0, -1):
u1, v1 = uv[i]
if nn[u1] < k or nn[v1] < k:
res[i - 1] = nk
continue
if nn[u1] == k:
q.append(u1)
nn[u1] -= 1
if not q and nn[v1] == k:
q.append(v1)
nn[v1] -= 1
if not q:
nn[u1] -= 1
nn[v1] -= 1
adj[u1].remove(v1)
adj[v1].remove(u1)
while q:
v = q.popleft()
nk -= 1
for u in adj[v]:
nn[u] -= 1
if nn[u] == k - 1:
q.append(u)
res[i - 1] = nk
return res
n, m, k = map(int, input().split())
a = [set() for i in range(n)]
uv = []
for i in range(m):
u, v = map(int, input().split())
a[u - 1].add(v - 1)
a[v - 1].add(u - 1)
uv.append((u-1, v-1))
res = solve(a, m, k, uv)
print(str(res)[1:-1].replace(' ', '').replace(',', '\n')) | python | code_algorithm | [
{
"input": "4 4 2\n2 3\n1 2\n1 3\n1 4\n",
"output": "0\n0\n3\n3\n"
},
{
"input": "5 8 2\n2 1\n4 2\n5 4\n5 2\n4 3\n5 1\n4 1\n3 2\n",
"output": "0\n0\n0\n3\n3\n4\n4\n5\n"
},
{
"input": "5 7 2\n1 5\n3 2\n2 5\n3 4\n1 2\n5 3\n1 3\n",
"output": "0\n0\n0\n0\n3\n4\n4\n"
},
{
"input":... | code_contests | python | 0 | beb0dd6a12442bd279058321cc62f55b |
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.
For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.
You have n cards with digits, and you want to use them to make as many phone numbers as possible. Each card must be used in at most one phone number, and you don't have to use all cards. The phone numbers do not necessarily have to be distinct.
Input
The first line contains an integer n β the number of cards with digits that you have (1 β€ n β€ 100).
The second line contains a string of n digits (characters "0", "1", ..., "9") s_1, s_2, β¦, s_n. The string will not contain any other characters, such as leading or trailing spaces.
Output
If at least one phone number can be made from these cards, output the maximum number of phone numbers that can be made. Otherwise, output 0.
Examples
Input
11
00000000008
Output
1
Input
22
0011223344556677889988
Output
2
Input
11
31415926535
Output
0
Note
In the first example, one phone number, "8000000000", can be made from these cards.
In the second example, you can make two phone numbers from the cards, for example, "80123456789" and "80123456789".
In the third example you can't make any phone number from the given cards.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
s = input()
k = s.count("8")
l = n - k
if k <= l//10: print(k)
else:
while k > l//10:
k -= 1
l += 1
print(min(k, l//10))
| python | code_algorithm | [
{
"input": "22\n0011223344556677889988\n",
"output": "2\n"
},
{
"input": "11\n00000000008\n",
"output": "1\n"
},
{
"input": "11\n31415926535\n",
"output": "0\n"
},
{
"input": "51\n882889888888689888850888388887688788888888888858888\n",
"output": "4\n"
},
{
"input"... | code_contests | python | 0.7 | b01666dd88e1ad0a807582f711932e08 |
You are given q queries in the following form:
Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i].
Can you answer all the queries?
Recall that a number x belongs to segment [l, r] if l β€ x β€ r.
Input
The first line contains one integer q (1 β€ q β€ 500) β the number of queries.
Then q lines follow, each containing a query given in the format l_i r_i d_i (1 β€ l_i β€ r_i β€ 10^9, 1 β€ d_i β€ 10^9). l_i, r_i and d_i are integers.
Output
For each query print one integer: the answer to this query.
Example
Input
5
2 4 2
5 10 4
3 10 1
1 2 3
4 6 5
Output
6
4
1
3
10
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
A = []
for i in range(n):
A = A+[input().split()]
for a in A:
if int(a[2]) < int(a[0]) or int(a[2]) > int(a[1]):
print(a[2])
else:
print(int(a[2])*(int(a[1])//int(a[2])+1))
| python | code_algorithm | [
{
"input": "5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5\n",
"output": "6\n4\n1\n3\n10\n"
},
{
"input": "20\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 1000000000 2\n1 100... | code_contests | python | 0.6 | 59abd6c42ba050b98fa6f7b72a5aaba5 |
An array of integers p_{1},p_{2}, β¦,p_{n} is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3,1,2], [1], [1,2,3,4,5] and [4,3,1,2]. The following arrays are not permutations: [2], [1,1], [2,3,4].
There is a hidden permutation of length n.
For each index i, you are given s_{i}, which equals to the sum of all p_{j} such that j < i and p_{j} < p_{i}. In other words, s_i is the sum of elements before the i-th element that are smaller than the i-th element.
Your task is to restore the permutation.
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^{5}) β the size of the permutation.
The second line contains n integers s_{1}, s_{2}, β¦, s_{n} (0 β€ s_{i} β€ (n(n-1))/(2)).
It is guaranteed that the array s corresponds to a valid permutation of length n.
Output
Print n integers p_{1}, p_{2}, β¦, p_{n} β the elements of the restored permutation. We can show that the answer is always unique.
Examples
Input
3
0 0 0
Output
3 2 1
Input
2
0 1
Output
1 2
Input
5
0 1 1 1 10
Output
1 4 3 2 5
Note
In the first example for each i there is no index j satisfying both conditions, hence s_i are always 0.
In the second example for i = 2 it happens that j = 1 satisfies the conditions, so s_2 = p_1.
In the third example for i = 2, 3, 4 only j = 1 satisfies the conditions, so s_2 = s_3 = s_4 = 1. For i = 5 all j = 1, 2, 3, 4 are possible, so s_5 = p_1 + p_2 + p_3 + p_4 = 10.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import stdin,stdout
class Tree(object):
def __init__(self,n):
self.tree=[0]*(4*n+10)
self.b=[0]*(n+10)
self.a=list(map(int,stdin.readline().split()))
self.n=n
def update(self,L,C,l,r,rt):
if l==r:
self.tree[rt]+=C
return
mid=(l+r)//2
if L<=mid:
self.update(L,C,l,mid,rt<<1)
else:
self.update(L,C,mid+1,r,rt<<1|1)
self.tree[rt]=self.tree[rt<<1]+self.tree[rt<<1|1]
def query(self,s,l,r,rt):
if l==r:
return l
mid=(l+r)//2
if self.tree[rt<<1]>s:
return self.query(s,l,mid,rt<<1)
else:
return self.query(s-self.tree[rt<<1],mid+1,r,rt<<1|1)
def slove(self):
for i in range(n):
self.update(i+1,i+1,1,n,1)
for i in range(n,0,-1):
self.b[i]=self.query(self.a[i-1],1,n,1)
self.update(self.b[i],-self.b[i],1,n,1)
for i in range(n):
stdout.write('%d '%(self.b[i+1]))
if __name__ == '__main__':
n=int(stdin.readline())
seg=Tree(n)
seg.slove() | python | code_algorithm | [
{
"input": "3\n0 0 0\n",
"output": "3 2 1 "
},
{
"input": "5\n0 1 1 1 10\n",
"output": "1 4 3 2 5 "
},
{
"input": "2\n0 1\n",
"output": "1 2 "
},
{
"input": "100\n0 0 57 121 57 0 19 251 19 301 19 160 57 578 664 57 19 50 0 621 91 5 263 34 5 96 713 649 22 22 22 5 108 198 1412 1... | code_contests | python | 0 | 604af8f068c0bed3738b6e00e0ab903d |
This is the easier version of the problem. In this version 1 β€ n, m β€ 100. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]:
* [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list);
* [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences.
Suppose that an additional non-negative integer k (1 β€ k β€ n) is given, then the subsequence is called optimal if:
* it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k;
* and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 β€ t β€ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example:
* [10, 20, 20] lexicographically less than [10, 21, 1],
* [7, 99, 99] is lexicographically less than [10, 21, 1],
* [10, 21, 0] is lexicographically less than [10, 21, 1].
You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 β€ k β€ n, 1 β€ pos_j β€ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.
For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input
The first line contains an integer n (1 β€ n β€ 100) β the length of the sequence a.
The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
The third line contains an integer m (1 β€ m β€ 100) β the number of requests.
The following m lines contain pairs of integers k_j and pos_j (1 β€ k β€ n, 1 β€ pos_j β€ k_j) β the requests.
Output
Print m integers r_1, r_2, ..., r_m (1 β€ r_j β€ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.
Examples
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
Note
In the first example, for a=[10,20,10] the optimal subsequences are:
* for k=1: [20],
* for k=2: [10,20],
* for k=3: [10,20,10].
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | # class SegmentTree(): # adapted from https://www.geeksforgeeks.org/segment-tree-efficient-implementation/
# def __init__(self,arr,func,initialRes=0):
# self.f=func
# self.N=len(arr)
# self.tree=[0 for _ in range(2*self.N)]
# self.initialRes=initialRes
# for i in range(self.N):
# self.tree[self.N+i]=arr[i]
# for i in range(self.N-1,0,-1):
# self.tree[i]=self.f(self.tree[i<<1],self.tree[i<<1|1])
# def updateTreeNode(self,idx,value): #update value at arr[idx]
# self.tree[idx+self.N]=value
# idx+=self.N
# i=idx
# while i>1:
# self.tree[i>>1]=self.f(self.tree[i],self.tree[i^1])
# i>>=1
# def query(self,l,r): #get sum (or whatever function) on interval [l,r] inclusive
# r+=1
# res=self.initialRes
# l+=self.N
# r+=self.N
# while l<r:
# if l&1:
# res=self.f(res,self.tree[l])
# l+=1
# if r&1:
# r-=1
# res=self.f(res,self.tree[r])
# l>>=1
# r>>=1
# return res
# def getMaxSegTree(arr):
# return SegmentTree(arr,lambda a,b:max(a,b),initialRes=-float('inf'))
# def getMinSegTree(arr):
# return SegmentTree(arr,lambda a,b:min(a,b),initialRes=float('inf'))
# def getSumSegTree(arr):
# return SegmentTree(arr,lambda a,b:a+b,initialRes=0)
from collections import Counter
def main():
# mlogn solution
n=int(input())
a=readIntArr()
b=sorted(a,reverse=True)
m=int(input())
allans=[]
for _ in range(m):
k,pos=readIntArr()
cnt=Counter(b[:k])
totalCnts=0
for x in a:
if cnt[x]>0:
cnt[x]-=1
totalCnts+=1
if totalCnts==pos:
allans.append(x)
break
multiLineArrayPrint(allans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(i,j):
print('? {} {}'.format(i,j))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(' '.join([str(x) for x in ans])))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main() | python | code_algorithm | [
{
"input": "3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3\n",
"output": "20\n10\n20\n10\n20\n10\n"
},
{
"input": "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4\n",
"output": "2\n3\n2\n3\n2\n3\n1\n1\n3\n"
},
{
"input": "2\n1 10\n3\n2 2\n2 1\n1 1\n",
"output": "10\n1\... | code_contests | python | 0.3 | 760b8bb2034c3becd8829ce071321ee1 |
There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1).
You're given k subsets A_1, β¦, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 β€ i_1 < i_2 < i_3 β€ k, A_{i_1} β© A_{i_2} β© A_{i_3} = β
.
In one operation, you can choose one of these k subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.
Let m_i be the minimum number of operations you have to do in order to make the i first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1 and n), they can be either off or on.
You have to compute m_i for all 1 β€ i β€ n.
Input
The first line contains two integers n and k (1 β€ n, k β€ 3 β
10^5).
The second line contains a binary string of length n, representing the initial state of each lamp (the lamp i is off if s_i = 0, on if s_i = 1).
The description of each one of the k subsets follows, in the following format:
The first line of the description contains a single integer c (1 β€ c β€ n) β the number of elements in the subset.
The second line of the description contains c distinct integers x_1, β¦, x_c (1 β€ x_i β€ n) β the elements of the subset.
It is guaranteed that:
* The intersection of any three subsets is empty;
* It's possible to make all lamps be simultaneously on using some operations.
Output
You must output n lines. The i-th line should contain a single integer m_i β the minimum number of operations required to make the lamps 1 to i be simultaneously on.
Examples
Input
7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
Output
1
2
3
3
3
3
3
Input
8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
Output
1
1
1
1
1
1
4
4
Input
5 3
00011
3
1 2 3
1
4
3
3 4 5
Output
1
1
1
1
1
Input
19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
Output
0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
Note
In the first example:
* For i = 1, we can just apply one operation on A_1, the final states will be 1010110;
* For i = 2, we can apply operations on A_1 and A_3, the final states will be 1100110;
* For i β₯ 3, we can apply operations on A_1, A_2 and A_3, the final states will be 1111111.
In the second example:
* For i β€ 6, we can just apply one operation on A_2, the final states will be 11111101;
* For i β₯ 7, we can apply operations on A_1, A_3, A_4, A_6, the final states will be 11111111.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import stdin
input = stdin.readline
n , k = [int(i) for i in input().split()]
pairs = [i + k for i in range(k)] + [i for i in range(k)]
initial_condition = list(map(lambda x: x == '1',input().strip()))
data = [i for i in range(2*k)]
constrain = [-1] * (2*k)
h = [0] * (2*k)
L = [1] * k + [0] * k
dp1 = [-1 for i in range(n)]
dp2 = [-1 for i in range(n)]
for i in range(k):
input()
inp = [int(j) for j in input().split()]
for s in inp:
if dp1[s-1] == -1:dp1[s-1] = i
else:dp2[s-1] = i
pfsums = 0
ans = []
def remove_pfsum(s1):
global pfsums
if constrain[s1] == 1:
pfsums -= L[s1]
elif constrain[pairs[s1]] == 1:
pfsums -= L[pairs[s1]]
else:
pfsums -= min(L[s1],L[pairs[s1]])
def sh(i):
while i != data[i]:
i = data[i]
return i
def upd_pfsum(s1):
global pfsums
if constrain[s1] == 1:
pfsums += L[s1]
elif constrain[pairs[s1]] == 1:
pfsums += L[pairs[s1]]
else:
pfsums += min(L[s1],L[pairs[s1]])
def ms(i,j):
i = sh(i) ; j = sh(j)
cons = max(constrain[i],constrain[j])
if h[i] < h[j]:
data[i] = j
L[j] += L[i]
constrain[j] = cons
return j
else:
data[j] = i
if h[i] == h[j]:
h[i] += 1
L[i] += L[j]
constrain[i] = cons
return i
for i in range(n):
if dp1[i] == -1 and dp2[i] == -1:
pass
elif dp2[i] == -1:
s1 = sh(dp1[i])
remove_pfsum(s1)
constrain[s1] = 0 if initial_condition[i] else 1
constrain[pairs[s1]] = 1 if initial_condition[i] else 0
upd_pfsum(s1)
else:
s1 = sh(dp1[i]) ; s2 = sh(dp2[i])
if s1 == s2 or pairs[s1] == s2:
pass
else:
remove_pfsum(s1)
remove_pfsum(s2)
if initial_condition[i]:
new_s1 = ms(s1,s2)
new_s2 = ms(pairs[s1],pairs[s2])
else:
new_s1 = ms(s1,pairs[s2])
new_s2 = ms(pairs[s1],s2)
pairs[new_s1] = new_s2
pairs[new_s2] = new_s1
upd_pfsum(new_s1)
ans.append(pfsums)
for i in ans:
print(i)
| python | code_algorithm | [
{
"input": "5 3\n00011\n3\n1 2 3\n1\n4\n3\n3 4 5\n",
"output": "1\n1\n1\n1\n1\n"
},
{
"input": "8 6\n00110011\n3\n1 3 8\n5\n1 2 5 6 7\n2\n6 8\n2\n3 5\n2\n4 7\n1\n2\n",
"output": "1\n1\n1\n1\n1\n1\n4\n4\n"
},
{
"input": "19 5\n1001001001100000110\n2\n2 3\n2\n5 6\n2\n8 9\n5\n12 13 14 15 16... | code_contests | python | 0 | ae86fea13f1ef4e812fa9f7d6a89219a |
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it.
Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'.
For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)
The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n).
We can show that there always exists a solution for the given constraints.
Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 50). Description of the test cases follows.
The first line of each test case contains one integers n (3 β€ n β€ 200).
The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'.
The sum of values of n doesn't exceed 200.
Output
For each test case output on the first line an integer c (0 β€ c β€ 2) β the number of inverted cells.
In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n).
Example
Input
3
4
S010
0001
1000
111F
3
S10
101
01F
5
S0101
00000
01111
11111
0001F
Output
1
3 4
2
1 2
2 1
0
Note
For the first test case, after inverting the cell, we get the following grid:
S010
0001
1001
111F
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | l=[]
for _ in range(int(input())):
n=int(input())
a=[]
for i in range(n):
a.append(list(input()))
if a[0][1]==a[1][0]:
if a[n-1][n-2]==a[n-2][n-1]:
if a[n-1][n-2]==a[0][1]:
l.append("2")
l.append("1 2")
l.append("2 1")
else:
l.append("0")
else:
if a[n-1][n-2]!=a[0][1]:
l.append("1")
l.append(str(n-1)+" "+str(n))
else:
l.append("1")
l.append(str(n)+" "+str(n-1))
else:
if a[n-1][n-2]==a[n-2][n-1]:
if a[n-1][n-2]!=a[0][1]:
l.append("1")
l.append("2 1")
else:
l.append("1")
l.append("1 2")
else:
if a[0][1]!=a[n-2][n-1]:
l.append("2")
l.append("1 2")
l.append(str(n-1)+" "+str(n))
else:
l.append("2")
l.append("2 1")
l.append(str(n - 1)+" "+ str(n))
for i in l:
print(i) | python | code_algorithm | [
{
"input": "3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F\n",
"output": "1\n3 4\n2\n1 2\n2 1\n0\n"
},
{
"input": "1\n3\nS01\n111\n00F\n",
"output": "2\n1 2\n2 3\n"
},
{
"input": "1\n5\nS0000\n00000\n00000\n00000\n0000F\n",
"output": "2\n1 2\n2 1... | code_contests | python | 0 | 0e7a1641aa74ffc84054534c56b96a9c |
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | inn = list(map(int, input().split(" ")))
r1 = inn[0]
r2 = inn[1]
inn = list(map(int, input().split(" ")))
c1 = inn[0]
c2 = inn[1]
inn = list(map(int, input().split(" ")))
d1 = inn[0]
d2 = inn[1]
x = int((d1+c1-r2)/2)
y = int(((2*r1)-d1-c1+r2)/2)
a = int(((2*c1)-d1-c1+r2)/2)
b = int((r2-(2*c1)+d1+c1)/2)
if x == y or x == a or x == b or y == a or y == b or a == b or x < 1 or x > 9 or y < 1 or y > 9 or a < 1 or a > 9 or b < 1 or b > 9:
print(-1)
else:
print(x, y)
print(a, b) | python | code_algorithm | [
{
"input": "1 2\n3 4\n5 6\n",
"output": "-1\n"
},
{
"input": "11 10\n13 8\n5 16\n",
"output": "4 7\n9 1\n"
},
{
"input": "3 7\n4 6\n5 5\n",
"output": "1 2\n3 4\n"
},
{
"input": "10 10\n10 10\n10 10\n",
"output": "-1\n"
},
{
"input": "3 14\n8 9\n10 7\n",
"outpu... | code_contests | python | 0.6 | 9e58991860e856dce4bee86fc9243d92 |
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def putin():
return map(int, input().split())
def sol():
n = int(input())
C = list(putin())
B = list(putin())
q = int(input())
x = int(input())
min_arr = [x]
min_part_sums = [x]
part_sums = [C[0]]
for i in range(1, n):
part_sums.append(part_sums[-1] + C[i])
for elem in B:
min_arr.append(min_arr[-1] + elem)
min_part_sums.append(min_arr[-1] + min_part_sums[-1])
for i in range(n):
if min_part_sums[i] > part_sums[i]:
return 0
if min_part_sums[0] > C[0]:
return 0
answer = [1] * (part_sums[0] - max(0, min_part_sums[0]) + 1)
for k in range(1, n):
new_answer = [0] * (part_sums[k] - max(0, min_part_sums[k]) + 1)
cnt = 1
window = answer[-1]
new_answer[-1] = window
while cnt <= len(new_answer) - 1:
cnt += 1
if cnt <= len(answer):
window += answer[-cnt]
if C[k] + 1 < cnt:
window -= answer[C[k] + 1 - cnt]
new_answer[-cnt] = window
answer = new_answer.copy()
m = 10 ** 9 + 7
return sum(answer) % m
print(sol()) | python | code_algorithm | [
{
"input": "3\n2 3 4\n2 1\n1\n-1\n",
"output": "56\n"
},
{
"input": "100\n95 54 23 27 51 58 94 34 29 95 53 53 8 5 64 32 17 62 14 37 26 95 27 85 94 37 85 72 88 69 43 9 60 3 48 26 81 48 89 56 34 28 2 63 26 6 13 19 99 41 70 24 92 41 9 73 52 42 34 98 16 82 7 81 28 80 18 33 90 69 19 13 51 96 8 21 86 32 9... | code_contests | python | 0 | b7f843cc7856e86bbd1dcf8832051cd5 |
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | num,wiz,per = map(int,input().split())
k = 0
while (k+wiz)/num*100 < per:
k += 1
print(k) | python | code_algorithm | [
{
"input": "1000 352 146\n",
"output": "1108\n"
},
{
"input": "10 1 14\n",
"output": "1\n"
},
{
"input": "20 10 50\n",
"output": "0\n"
},
{
"input": "7879 2590 2818\n",
"output": "219441\n"
},
{
"input": "78 28 27\n",
"output": "0\n"
},
{
"input": "917... | code_contests | python | 1 | 448467bd18f58351ae6cb788118b535b |
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".
We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").
The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.
A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.
Notice, that any year between 2013 and 2015 is not a leap year.
Input
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
Output
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
Examples
Input
777-444---21-12-2013-12-2013-12-2013---444-777
Output
13-12-2013
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | s=input()
n=len(s)
l=list("0987654321")
cnt={}
for i in range(n-9):
t=s[i:i+10]
if t[0] in l and t[1] in l and t[2]=="-" and t[3] in l and t[4] in l and t[5]=="-" and t[6] in l and t[7] in l and t[8] in l and t[9] in l:
if 2013<=int(t[6:11])<=2015 and 1<=int(t[3:5])<=12:
if int(t[3:5]) in [1,3,5,7,8,10,12] and 1<=int(t[0:2])<=31:
if not t in cnt:
cnt[t]=1
else:
cnt[t]+=1
elif int(t[3:5]) in [4,6,9,11] and 1<=int(t[0:2])<=30:
if not t in cnt:
cnt[t]=1
else:
cnt[t]+=1
elif int(t[3:5])==2 and 1<=int(t[0:2])<=28:
if not t in cnt:
cnt[t]=1
else:
cnt[t]+=1
print(max(cnt,key=cnt.get)) | python | code_algorithm | [
{
"input": "777-444---21-12-2013-12-2013-12-2013---444-777\n",
"output": "13-12-2013\n"
},
{
"input": "12-12-201312-12-201312-12-201313--12-201313--12-201313--12-201313--12-201313--12-201313--12-201313--12-201313--12-2013\n",
"output": "12-12-2013\n"
},
{
"input": "01--01--2013-12-2013-0... | code_contests | python | 0 | 9d239ad589285ee12c32b4c7a30ff051 |
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like any other new candle.
Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.
Input
The single line contains two integers, a and b (1 β€ a β€ 1000; 2 β€ b β€ 1000).
Output
Print a single integer β the number of hours Vasily can light up the room for.
Examples
Input
4 2
Output
7
Input
6 3
Output
8
Note
Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | a, b = map(int, input().split())
c, s = a, 0
while a >= b:
s += a // b
a = (a // b) + (a % b)
print(s + c)
| python | code_algorithm | [
{
"input": "4 2\n",
"output": "7\n"
},
{
"input": "6 3\n",
"output": "8\n"
},
{
"input": "5 3\n",
"output": "7\n"
},
{
"input": "1000 3\n",
"output": "1499\n"
},
{
"input": "777 17\n",
"output": "825\n"
},
{
"input": "4 3\n",
"output": "5\n"
},
... | code_contests | python | 1 | 8915a1a694bf86827f735bc79cf88e2d |
To celebrate the opening of the Winter Computer School the organizers decided to buy in n liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles 0.5, 1 and 2 liters in volume. At that, there are exactly a bottles 0.5 in volume, b one-liter bottles and c of two-liter ones. The organizers have enough money to buy any amount of cola. What did cause the heated arguments was how many bottles of every kind to buy, as this question is pivotal for the distribution of cola among the participants (and organizers as well).
Thus, while the organizers are having the argument, discussing different variants of buying cola, the Winter School can't start. Your task is to count the number of all the possible ways to buy exactly n liters of cola and persuade the organizers that this number is too large, and if they keep on arguing, then the Winter Computer School will have to be organized in summer.
All the bottles of cola are considered indistinguishable, i.e. two variants of buying are different from each other only if they differ in the number of bottles of at least one kind.
Input
The first line contains four integers β n, a, b, c (1 β€ n β€ 10000, 0 β€ a, b, c β€ 5000).
Output
Print the unique number β the solution to the problem. If it is impossible to buy exactly n liters of cola, print 0.
Examples
Input
10 5 5 5
Output
9
Input
3 0 0 2
Output
0
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def nik(rudy,x,y,z,cot):
for i in range(z+1):
for j in range(y+1):
t = rudy - i*2 -j
if t>=0 and x*0.5 >= t:
cot+=1
return cot
rudy, x, y, z = list(map(int,input().split()))
cot = 0
print(nik(rudy,x,y,z,cot))
| python | code_algorithm | [
{
"input": "10 5 5 5\n",
"output": "9\n"
},
{
"input": "3 0 0 2\n",
"output": "0\n"
},
{
"input": "10 20 10 5\n",
"output": "36\n"
},
{
"input": "20 1 2 3\n",
"output": "0\n"
},
{
"input": "7 2 2 2\n",
"output": "1\n"
},
{
"input": "25 10 5 10\n",
... | code_contests | python | 0 | 43b30ec367ef72433f9dcadacd92e159 |
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared β the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
Input
The first line of the input contains integer n (3 β€ n β€ 105) β the initial number of compilation errors.
The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the errors the compiler displayed for the first time.
The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 β the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one.
The fourth line contains n - 2 space-separated integers Ρ1, Ρ2, ..., Ρn - 2 β the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
Output
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
Examples
Input
5
1 5 8 123 7
123 7 5 1
5 1 7
Output
8
123
Input
6
1 4 3 3 5 7
3 7 5 4 3
4 3 7 5
Output
1
3
Note
In the first test sample B first corrects the error number 8, then the error number 123.
In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
a_sum = sum(map(int, input().split()))
b_sum = sum(map(int, input().split()))
c_sum = sum(map(int, input().split()))
print(a_sum - b_sum)
print(b_sum - c_sum) | python | code_algorithm | [
{
"input": "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5\n",
"output": "1\n3\n"
},
{
"input": "5\n1 5 8 123 7\n123 7 5 1\n5 1 7\n",
"output": "8\n123\n"
},
{
"input": "3\n1 2 3\n3 2\n2\n",
"output": "1\n3\n"
},
{
"input": "3\n84 30 9\n9 84\n9\n",
"output": "30\n84\n"
},
{
"... | code_contests | python | 0.7 | c9cd3f8280a7cdbc60d57c9ebe1ce496 |
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of trees.
Next n lines contain pairs of integers xi, hi (1 β€ xi, hi β€ 109) β the coordinate and the height of the Ρ-th tree.
The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
Output
Print a single number β the maximum number of trees that you can cut down by the given rules.
Examples
Input
5
1 2
2 1
5 10
10 9
19 1
Output
3
Input
5
1 2
2 1
5 10
10 9
20 1
Output
4
Note
In the first sample you can fell the trees like that:
* fell the 1-st tree to the left β now it occupies segment [ - 1;1]
* fell the 2-nd tree to the right β now it occupies segment [2;3]
* leave the 3-rd tree β it occupies point 5
* leave the 4-th tree β it occupies point 10
* fell the 5-th tree to the right β now it occupies segment [19;20]
In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | ll=lambda:map(int,input().split())
t=lambda:int(input())
ss=lambda:input()
#from math import log10 ,log2,ceil,factorial as f,gcd
#from itertools import combinations_with_replacement as cs
#from functools import reduce
#from bisect import bisect_right as br
#from collections import Counter
n=t()
x,h=[],[]
for _ in range(n):
a,b=ll()
x.append(a)
h.append(b)
if n>=2:
c=2
tx=x[0]
for i in range(1,n-1):
if x[i]-tx>h[i]:
tx=x[i]
c+=1
elif x[i+1]-x[i]>h[i]:
tx=x[i]+h[i]
c+=1
else:
tx=x[i]
print(c)
else:
print(1) | python | code_algorithm | [
{
"input": "5\n1 2\n2 1\n5 10\n10 9\n20 1\n",
"output": "4\n"
},
{
"input": "5\n1 2\n2 1\n5 10\n10 9\n19 1\n",
"output": "3\n"
},
{
"input": "4\n10 4\n15 1\n19 3\n20 1\n",
"output": "4\n"
},
{
"input": "2\n1 999999999\n1000000000 1000000000\n",
"output": "2\n"
},
{
... | code_contests | python | 0 | 27cddf12656da9ed27befa5451b17836 |
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
Input
The first line of the input contains integers n and m (1 β€ n, m β€ 100) β the number of buttons and the number of bulbs respectively.
Each of the next n lines contains xi (0 β€ xi β€ m) β the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 β€ yij β€ m) β the numbers of these bulbs.
Output
If it's possible to turn on all m bulbs print "YES", otherwise print "NO".
Examples
Input
3 4
2 1 4
3 1 3 1
1 2
Output
YES
Input
3 3
1 1
1 2
1 1
Output
NO
Note
In the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
nm = input().split()
n = int(nm[0])
m = int(nm[1])
lis = [ 0 for i in range(m+1)]
for _ in range(n) :
inp = list(map(int, input().split()))
inp.pop(0)
for i in inp:
lis[i]=1
prev = i
if sum(lis)==m:
print("YES")
else:
print("NO") | python | code_algorithm | [
{
"input": "3 4\n2 1 4\n3 1 3 1\n1 2\n",
"output": "YES\n"
},
{
"input": "3 3\n1 1\n1 2\n1 1\n",
"output": "NO\n"
},
{
"input": "3 4\n1 1\n1 2\n1 3\n",
"output": "NO\n"
},
{
"input": "1 100\n99 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 3... | code_contests | python | 1 | 1e0fc159cc586e0b93922ac769ee474a |
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.
The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.
You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.
Input
First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 β€ n β€ 1000), the number of days.
Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person.
The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.
Output
Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.
Examples
Input
ross rachel
4
ross joey
rachel phoebe
phoebe monica
monica chandler
Output
ross rachel
joey rachel
joey phoebe
joey monica
joey chandler
Input
icm codeforces
1
codeforces technex
Output
icm codeforces
icm technex
Note
In first example, the killer starts with ross and rachel.
* After day 1, ross is killed and joey appears.
* After day 2, rachel is killed and phoebe appears.
* After day 3, phoebe is killed and monica appears.
* After day 4, monica is killed and chandler appears.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def main():
l = input().split()
print(*l)
for _ in range(int(input())):
a, b = input().split()
l[a == l[1]] = b
print(*l)
if __name__ == '__main__':
main()
| python | code_algorithm | [
{
"input": "icm codeforces\n1\ncodeforces technex\n",
"output": "icm codeforces\nicm technex\n"
},
{
"input": "ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler\n",
"output": "ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler\n"
},
{
"input": "wwwww... | code_contests | python | 0.3 | f7468dba19ad098239fa7efec4acc4cb |
There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet β the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:
* alloc n β to allocate n bytes of the memory and return the allocated block's identifier x;
* erase x β to erase the block with the identifier x;
* defragment β to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order;
The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.
The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.
The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.
The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.
In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.
You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.
Input
The first line of the input data contains two positive integers t and m (1 β€ t β€ 100;1 β€ m β€ 100), where t β the amount of operations given to the memory manager for processing, and m β the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 β€ n β€ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.
Output
Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.
Examples
Input
6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6
Output
1
2
NULL
3
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | t, m = map(int, input().split())
disk = [False] * m
req = 0
for i in range(t):
inp = input().split()
if inp[0][0] == "a":
c = 0
inp[1] = int(inp[1])
for j in range(m):
if disk[j]:
c = 0
else:
c += 1
if c == inp[1]:
req += 1
print(req)
for j in range(j - inp[1] + 1, j + 1):
disk[j] = req
break
if c < inp[1]:
print("NULL")
elif inp[0][0] == "e":
inp[1] = int(inp[1])
if inp[1] > req:
print("ILLEGAL_ERASE_ARGUMENT")
continue
if not inp[1] in disk:
print("ILLEGAL_ERASE_ARGUMENT")
continue
if inp[1] < 1:
print("ILLEGAL_ERASE_ARGUMENT")
continue
for j in range(m):
if disk[j] == inp[1]:
disk[j] = False
elif inp[0][0] == "d":
for j in range(m):
if disk[j]:
_j = j
while _j > 0 and not disk[_j - 1]:
disk[_j - 1] = disk[_j]
disk[_j] = False
_j -= 1
| python | code_algorithm | [
{
"input": "6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6\n",
"output": "1\n2\nNULL\n3\n"
},
{
"input": "3 1\nerase -1\nerase 0\nerase -2147483648\n",
"output": "ILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n"
},
{
"input": "26 25\ndefragment\ner... | code_contests | python | 0 | 26e6f8ab82989c487d130c5a82b327ab |
Some time ago Mister B detected a strange signal from the space, which he started to study.
After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.
Let's define the deviation of a permutation p as <image>.
Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.
Let's denote id k (0 β€ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example:
* k = 0: shift p1, p2, ... pn,
* k = 1: shift pn, p1, ... pn - 1,
* ...,
* k = n - 1: shift p2, p3, ... pn, p1.
Input
First line contains single integer n (2 β€ n β€ 106) β the length of the permutation.
The second line contains n space-separated integers p1, p2, ..., pn (1 β€ pi β€ n) β the elements of the permutation. It is guaranteed that all elements are distinct.
Output
Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.
Examples
Input
3
1 2 3
Output
0 0
Input
3
2 3 1
Output
0 1
Input
3
3 2 1
Output
2 1
Note
In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.
In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.
In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import stdin
def main():
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
inf = [0] * (n + 1)
curr = 0
d = 0
for i in range(n):
curr += abs(i + 1 - a[i])
if a[i] > i + 1:
d += 1
inf[a[i] - i - 1] += 1
elif a[i] <= i + 1:
d -= 1
if a[i] == i + 1:
inf[0] += 1
else:
inf[a[i] + n - i - 1] += 1
best = curr
num = 0
for i in range(n):
curr -= d
curr -= 1
curr = curr - abs(a[n - i - 1] - n) + abs(a[n - i - 1] - 1)
d += 2
d -= inf[i + 1] * 2
if curr < best:
best = curr
num = i + 1
print(best, num)
main() | python | code_algorithm | [
{
"input": "3\n3 2 1\n",
"output": "2 1\n"
},
{
"input": "3\n1 2 3\n",
"output": "0 0\n"
},
{
"input": "3\n2 3 1\n",
"output": "0 1\n"
},
{
"input": "4\n1 2 4 3\n",
"output": "2 0\n"
},
{
"input": "4\n2 1 4 3\n",
"output": "4 0\n"
},
{
"input": "10\n1 ... | code_contests | python | 0.5 | 65f9e6f27980b75233674c2fcfd9bf07 |
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment.
Fortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange.
Berland chemists are aware of n materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each i (2 β€ i β€ n) there exist two numbers xi and ki that denote a possible transformation: ki kilograms of material xi can be transformed into 1 kilogram of material i, and 1 kilogram of material i can be transformed into 1 kilogram of material xi. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is always an integer number of kilograms.
For each i (1 β€ i β€ n) Igor knows that the experiment requires ai kilograms of material i, and the laboratory contains bi kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?
Input
The first line contains one integer number n (1 β€ n β€ 105) β the number of materials discovered by Berland chemists.
The second line contains n integer numbers b1, b2... bn (1 β€ bi β€ 1012) β supplies of BerSU laboratory.
The third line contains n integer numbers a1, a2... an (1 β€ ai β€ 1012) β the amounts required for the experiment.
Then n - 1 lines follow. j-th of them contains two numbers xj + 1 and kj + 1 that denote transformation of (j + 1)-th material (1 β€ xj + 1 β€ j, 1 β€ kj + 1 β€ 109).
Output
Print YES if it is possible to conduct an experiment. Otherwise print NO.
Examples
Input
3
1 2 3
3 2 1
1 1
1 1
Output
YES
Input
3
3 2 1
1 2 3
1 1
1 2
Output
NO
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
# @profile
def main():
f = sys.stdin
# f = open('input.txt', 'r')
# fo = open('log.txt', 'w')
n = int(f.readline())
# b = []
# for i in range(n):
# b.append()
b = list(map(int, f.readline().strip().split(' ')))
a = list(map(int, f.readline().strip().split(' ')))
# return
b = [b[i] - a[i] for i in range(n)]
c = [[0, 0]]
for i in range(n - 1):
line = f.readline().strip().split(' ')
c.append([int(line[0]), int(line[1])])
# print(c)
for i in range(n - 1, 0, -1):
# print(i)
fa = c[i][0] - 1
if b[i] >= 0:
b[fa] += b[i]
else:
b[fa] += b[i] * c[i][1]
if b[fa] < -1e17:
print('NO')
return 0
# for x in b:
# fo.write(str(x) + '\n')
if b[0] >= 0:
print('YES')
else:
print('NO')
main()
| python | code_algorithm | [
{
"input": "3\n3 2 1\n1 2 3\n1 1\n1 2\n",
"output": "NO\n"
},
{
"input": "3\n1 2 3\n3 2 1\n1 1\n1 1\n",
"output": "YES\n"
},
{
"input": "5\n27468 7465 74275 40573 40155\n112071 76270 244461 264202 132397\n1 777133331\n2 107454154\n3 652330694\n4 792720519\n",
"output": "NO\n"
},
... | code_contests | python | 0 | 6320bf5975516c11a22238f42feb9d0e |
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.
She starts with 0 money on her account.
In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.
In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.
It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».
Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
Input
The first line contains two integers n, d (1 β€ n β€ 105, 1 β€ d β€ 109) βthe number of days and the money limitation.
The second line contains n integer numbers a1, a2, ... an ( - 104 β€ ai β€ 104), where ai represents the transaction in i-th day.
Output
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
Examples
Input
5 10
-1 5 0 -5 3
Output
0
Input
3 4
-10 0 20
Output
-1
Input
5 10
-5 0 10 -11 0
Output
2
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue, bisect
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7
sys.setrecursionlimit(1000000)
n, d = map(int, input().split())
a = list(map(int, input().split()))
p = [0 for i in range(n)]
for i in range(n):
p[i] = p[i-1]+a[i]
mx = [-1 for i in range(n)]
mx[-1] = p[-1]
for i in range(n-2, -1, -1):
mx[i] = max(mx[i+1], p[i])
c = 0
ans = 0
for i in range(n):
p[i] += c
if p[i] > d:
print(-1)
exit()
if a[i] != 0 or p[i] >= 0: continue
av = d-(mx[i]+c)
if -p[i] > av:
print(-1)
exit()
ans += 1
c = d-mx[i]
print(ans) | python | code_algorithm | [
{
"input": "5 10\n-5 0 10 -11 0\n",
"output": "2\n"
},
{
"input": "5 10\n-1 5 0 -5 3\n",
"output": "0\n"
},
{
"input": "3 4\n-10 0 20\n",
"output": "-1\n"
},
{
"input": "9 13\n6 14 19 5 -5 6 -10 20 8\n",
"output": "-1\n"
},
{
"input": "8 9\n6 -1 5 -5 -8 -7 -8 -7\n... | code_contests | python | 0 | 33225e8e01201c2b2b907a4331fd0dac |
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.
Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length ai if she chooses the i-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.
See the examples for better understanding.
Input
The first line of input contains two integer numbers n and k (1 β€ n, k β€ 100) β the number of buckets and the length of the garden, respectively.
The second line of input contains n integer numbers ai (1 β€ ai β€ 100) β the length of the segment that can be watered by the i-th bucket in one hour.
It is guaranteed that there is at least one bucket such that it is possible to water the garden in integer number of hours using only this bucket.
Output
Print one integer number β the minimum number of hours required to water the garden.
Examples
Input
3 6
2 3 5
Output
2
Input
6 7
1 2 3 4 5 6
Output
7
Note
In the first test the best option is to choose the bucket that allows to water the segment of length 3. We can't choose the bucket that allows to water the segment of length 5 because then we can't water the whole garden.
In the second test we can choose only the bucket that allows us to water the segment of length 1.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def is_prime(a):
return all(a % i for i in range(2, a))
n, k = map(int, input().split())
l = [int(x) for x in input().split()]
if is_prime(k):
if k in l:
print(1)
else:
print(k)
else:
ll = []
for i in range(len(l)):
if k % l[i] == 0:
ll.append(l[i])
print(k // max(ll))
| python | code_algorithm | [
{
"input": "3 6\n2 3 5\n",
"output": "2\n"
},
{
"input": "6 7\n1 2 3 4 5 6\n",
"output": "7\n"
},
{
"input": "3 7\n3 2 1\n",
"output": "7\n"
},
{
"input": "4 97\n97 1 50 10\n",
"output": "1\n"
},
{
"input": "5 25\n24 5 15 25 23\n",
"output": "1\n"
},
{
... | code_contests | python | 0.5 | 3b105121cca3287972bd6dd6b9210cef |
You and your friend are participating in a TV show "Run For Your Prize".
At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend β at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.
You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.
Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.
What is the minimum number of seconds it will take to pick up all the prizes?
Input
The first line contains one integer n (1 β€ n β€ 105) β the number of prizes.
The second line contains n integers a1, a2, ..., an (2 β€ ai β€ 106 - 1) β the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.
Output
Print one integer β the minimum number of seconds it will take to collect all prizes.
Examples
Input
3
2 3 9
Output
8
Input
2
2 999995
Output
5
Note
In the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.
In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | input()
a=list(map(int,input().split()))
ans=0
for x in a:
z=min(x-1,1000000-x)
ans=max(z,ans)
print(ans)
| python | code_algorithm | [
{
"input": "2\n2 999995\n",
"output": "5\n"
},
{
"input": "3\n2 3 9\n",
"output": "8\n"
},
{
"input": "3\n500000 500001 500002\n",
"output": "499999\n"
},
{
"input": "1\n505050\n",
"output": "494950\n"
},
{
"input": "2\n999998 999999\n",
"output": "2\n"
},
... | code_contests | python | 0.2 | 2ccad2343428afdd712d95cd5fd34968 |
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked and no post lamp can be placed there.
There are post lamps of different types which differ only by their power. When placed in position x, post lamp of power l illuminates the segment [x; x + l]. The power of each post lamp is always a positive integer number.
The post lamp shop provides an infinite amount of lamps of each type from power 1 to power k. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power l cost a_l each.
What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power 3 in position n - 1 (even though its illumination zone doesn't completely belong to segment [0; n]).
Input
The first line contains three integer numbers n, m and k (1 β€ k β€ n β€ 10^6, 0 β€ m β€ n) β the length of the segment of the street Adilbek wants to illuminate, the number of the blocked positions and the maximum power of the post lamp available.
The second line contains m integer numbers s_1, s_2, ..., s_m (0 β€ s_1 < s_2 < ... s_m < n) β the blocked positions.
The third line contains k integer numbers a_1, a_2, ..., a_k (1 β€ a_i β€ 10^6) β the costs of the post lamps.
Output
Print the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street.
If illumintaing the entire segment [0; n] is impossible, print -1.
Examples
Input
6 2 3
1 3
1 2 3
Output
6
Input
4 3 4
1 2 3
1 10 100 1000
Output
1000
Input
5 1 5
0
3 3 3 3 3
Output
-1
Input
7 4 3
2 4 5 6
3 14 15
Output
-1
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
from array import array
n, m, k = map(int, input().split())
block = list(map(int, input().split()))
a = [0] + list(map(int, input().split()))
if block and block[0] == 0:
print(-1)
exit()
prev = array('i', list(range(n)))
for x in block:
prev[x] = -1
for i in range(1, n):
if prev[i] == -1:
prev[i] = prev[i-1]
inf = ans = 10**18
for i in range(1, k+1):
s = 0
cost = 0
while True:
cost += a[i]
t = s+i
if t >= n:
break
if prev[t] == s:
cost = inf
break
s = prev[t]
ans = min(ans, cost)
print(ans if ans < inf else -1)
| python | code_algorithm | [
{
"input": "5 1 5\n0\n3 3 3 3 3\n",
"output": "-1\n"
},
{
"input": "4 3 4\n1 2 3\n1 10 100 1000\n",
"output": "1000\n"
},
{
"input": "7 4 3\n2 4 5 6\n3 14 15\n",
"output": "-1\n"
},
{
"input": "6 2 3\n1 3\n1 2 3\n",
"output": "6\n"
},
{
"input": "3 1 2\n2\n1 1\n",... | code_contests | python | 0 | da0767aaf952b30a8e07d9d301bd2179 |
At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector Π:
* Turn the vector by 90 degrees clockwise.
* Add to the vector a certain vector C.
Operations could be performed in any order any number of times.
Can Gerald cope with the task?
Input
The first line contains integers x1 ΠΈ y1 β the coordinates of the vector A ( - 108 β€ x1, y1 β€ 108). The second and the third line contain in the similar manner vectors B and C (their coordinates are integers; their absolute value does not exceed 108).
Output
Print "YES" (without the quotes) if it is possible to get vector B using the given operations. Otherwise print "NO" (without the quotes).
Examples
Input
0 0
1 1
0 1
Output
YES
Input
0 0
1 1
1 1
Output
YES
Input
0 0
1 1
2 2
Output
NO
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
def ok(xa, ya):
x, y = xb - xa, yb - ya
d = math.gcd(abs(xc), abs(yc))
if xc == 0 and yc == 0:
return x == 0 and y == 0
if xc == 0:
return x % yc == 0 and y % yc == 0
if yc == 0:
return x % xc == 0 and y % xc == 0
if (x % d != 0) or (y % d != 0):
return 0
a, b, c1, c2 = xc // d, yc // d, x // d, -y // d
if a == 0 and b == 0:
return c1 == 0 and c2 == 0
if (c1 * b + c2 * a) % (a * a + b * b) != 0:
return 0
yy = (c1 * b + c2 * a) / (a * a + b * b)
if a == 0:
return (c2 - a * yy) % b == 0
else:
return (c1 - b * yy) % a == 0
xa, ya = map(int,input().split())
xb, yb = map(int,input().split())
xc, yc = map(int,input().split())
if ok(xa, ya) or ok(-ya, xa) or ok(-xa, -ya) or ok(ya, -xa):
print('YES')
else:
print('NO')
| python | code_algorithm | [
{
"input": "0 0\n1 1\n1 1\n",
"output": "YES\n"
},
{
"input": "0 0\n1 1\n0 1\n",
"output": "YES\n"
},
{
"input": "0 0\n1 1\n2 2\n",
"output": "NO\n"
},
{
"input": "3 1\n-2 3\n-2 -2\n",
"output": "NO\n"
},
{
"input": "-8916 9282\n2666 2344\n9109 -2730\n",
"outp... | code_contests | python | 0 | 38abe6c6854f1adfc90fbd5ef9e809b3 |
Awruk is taking part in elections in his school. It is the final round. He has only one opponent β Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from this person. Of course 0 β€ k - a_i holds.
Awruk knows that if he loses his life is over. He has been speaking a lot with his friends and now he knows a_1, a_2, ..., a_n β how many votes for Elodreip each student wants to give. Now he wants to change the number k to win the elections. Of course he knows that bigger k means bigger chance that somebody may notice that he has changed something and then he will be disqualified.
So, Awruk knows a_1, a_2, ..., a_n β how many votes each student will give to his opponent. Help him select the smallest winning number k. In order to win, Awruk needs to get strictly more votes than Elodreip.
Input
The first line contains integer n (1 β€ n β€ 100) β the number of students in the school.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 100) β the number of votes each student gives to Elodreip.
Output
Output the smallest integer k (k β₯ max a_i) which gives Awruk the victory. In order to win, Awruk needs to get strictly more votes than Elodreip.
Examples
Input
5
1 1 1 5 1
Output
5
Input
5
2 2 3 2 2
Output
5
Note
In the first example, Elodreip gets 1 + 1 + 1 + 5 + 1 = 9 votes. The smallest possible k is 5 (it surely can't be less due to the fourth person), and it leads to 4 + 4 + 4 + 0 + 4 = 16 votes for Awruk, which is enough to win.
In the second example, Elodreip gets 11 votes. If k = 4, Awruk gets 9 votes and loses to Elodreip.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
n = int(input())
l= list(map(int,input().split()))
s = 2*sum(l)
z= s/n
p = max(l)
an = int(z+1)
print(max(p,an)) | python | code_algorithm | [
{
"input": "5\n2 2 3 2 2\n",
"output": "5\n"
},
{
"input": "5\n1 1 1 5 1\n",
"output": "5\n"
},
{
"input": "3\n1 2 6\n",
"output": "7\n"
},
{
"input": "10\n7 7 7 7 7 7 7 7 7 7\n",
"output": "15\n"
},
{
"input": "76\n13 13 5 6 20 20 6 1 18 18 13 15 20 3 9 11 3 11 3... | code_contests | python | 0.8 | 6e253981a563942c19cbc4489a791381 |
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
import math
import bisect
from math import sqrt
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def rinput(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7
n, m = rinput()
p = [0] + get_list()
d = {i:set() for i in range(1, n+1)}
for _ in range(m):
u, v = rinput()
d[u].add(v)
last = p[n]
target = n
for i in range(n-1, 0, -1):
for j in range(i, target):
if p[j+1] in d[p[j]]:
p[j], p[j+1] = p[j+1], p[j]
else:
break
if p[target]!=last:
target -= 1
print(n-target)
# 3 1 4 5 2 | python | code_algorithm | [
{
"input": "5 2\n3 1 5 4 2\n5 2\n5 4\n",
"output": "1\n"
},
{
"input": "3 3\n3 1 2\n1 2\n3 1\n3 2\n",
"output": "2\n"
},
{
"input": "2 1\n1 2\n1 2\n",
"output": "1\n"
},
{
"input": "10 23\n6 9 8 10 4 3 7 1 5 2\n7 2\n3 2\n2 4\n2 3\n7 5\n6 4\n10 7\n7 1\n6 8\n6 2\n8 10\n3 5\n3 1... | code_contests | python | 0 | e394c4bb4a3624ee6c6039c8cc801fcf |
You are given a string s consisting of n lowercase Latin letters.
Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from position l to position r is s[l; r] = s_l s_{l + 1} ... s_r.
You have to choose exactly one of the substrings of the given string and reverse it (i. e. make s[l; r] = s_r s_{r - 1} ... s_l) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.
If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.
String x is lexicographically less than string y, if either x is a prefix of y (and x β y), or there exists such i (1 β€ i β€ min(|x|, |y|)), that x_i < y_i, and for any j (1 β€ j < i) x_j = y_j. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languagesββ.
Input
The first line of the input contains one integer n (2 β€ n β€ 3 β
10^5) β the length of s.
The second line of the input contains the string s of length n consisting only of lowercase Latin letters.
Output
If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices l and r (1 β€ l < r β€ n) denoting the substring you have to reverse. If there are multiple answers, you can print any.
Examples
Input
7
abacaba
Output
YES
2 5
Input
6
aabcfg
Output
NO
Note
In the first testcase the resulting string is "aacabba".
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
def main():
n = input()
s = input()
for i in range(len(s)-1):
if s[i]>s[i+1]:
print('YES')
print(i+1, i+2)
return
print('NO')
main() | python | code_algorithm | [
{
"input": "7\nabacaba\n",
"output": "YES\n2 3\n"
},
{
"input": "6\naabcfg\n",
"output": "NO\n"
},
{
"input": "6\nbabcdc\n",
"output": "YES\n1 2\n"
},
{
"input": "5\nbadec\n",
"output": "YES\n1 2\n"
},
{
"input": "3\naba\n",
"output": "YES\n2 3\n"
},
{
... | code_contests | python | 0.5 | e4135095723a249bea775a903cb8b6ff |
This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n.
A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.
Let's denote a function that alternates digits of two numbers f(a_1 a_2 ... a_{p - 1} a_p, b_1 b_2 ... b_{q - 1} b_q), where a_1 ... a_p and b_1 ... b_q are digits of two integers written in the decimal notation without leading zeros.
In other words, the function f(x, y) alternately shuffles the digits of the numbers x and y by writing them from the lowest digits to the older ones, starting with the number y. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.
For example: $$$f(1111, 2222) = 12121212 f(7777, 888) = 7787878 f(33, 44444) = 4443434 f(555, 6) = 5556 f(111, 2222) = 2121212$$$
Formally,
* if p β₯ q then f(a_1 ... a_p, b_1 ... b_q) = a_1 a_2 ... a_{p - q + 1} b_1 a_{p - q + 2} b_2 ... a_{p - 1} b_{q - 1} a_p b_q;
* if p < q then f(a_1 ... a_p, b_1 ... b_q) = b_1 b_2 ... b_{q - p} a_1 b_{q - p + 1} a_2 ... a_{p - 1} b_{q - 1} a_p b_q.
Mishanya gives you an array consisting of n integers a_i, your task is to help students to calculate β_{i = 1}^{n}β_{j = 1}^{n} f(a_i, a_j) modulo 998 244 353.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of elements in the array. The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the elements of the array.
Output
Print the answer modulo 998 244 353.
Examples
Input
3
12 3 45
Output
12330
Input
2
123 456
Output
1115598
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from collections import Counter
n = int(input())
a = list(map(int, input().split()))
l = [len(str(i)) for i in a]
c = Counter(l)
cl = [c[i] for i in range(1,11)]
M = 998244353
pad = lambda a, d: a%d + (a - a%d) * 10
#print(a, l, c, cl)
ans = 0
for i in a:
il = len(str(i)) # let's calculate it again to avoid zip and enumerate
#print('processing', i, ans)
t = i
for p in range(10):
#if not cl[p]: continue
i = pad(i, 100**p)
#print('top pad', p, 'is', i, 'there are', cl[p])
ans = (ans + i * cl[p]) % M
i = t # restore
for p in range(10):
#if not cl[p]: continue
i = pad(i, 10 * 100**p)
#print('bottom pad', p, 'is', i, 'there are', cl[p])
ans = (ans + i * cl[p]) % M
print(ans)
| python | code_algorithm | [
{
"input": "3\n12 3 45\n",
"output": "12330\n"
},
{
"input": "2\n123 456\n",
"output": "1115598\n"
},
{
"input": "20\n76 86 70 7 16 24 10 62 26 29 40 65 55 49 34 55 92 47 43 100\n",
"output": "2178920\n"
},
{
"input": "100\n6591 1074 3466 3728 549 5440 533 3543 1536 2967 1587... | code_contests | python | 0 | d138b941c27c8a78ddb1fa1b00dbc7a4 |
Alice is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.
Each time she can do one of two operations:
1. take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);
2. take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones).
She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has 0 stones. Can you help her?
Input
The first line contains one integer t (1 β€ t β€ 100) β the number of test cases. Next t lines describe test cases in the following format:
Line contains three non-negative integers a, b and c, separated by spaces (0 β€ a,b,c β€ 100) β the number of stones in the first, the second and the third heap, respectively.
In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied.
Output
Print t lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer β the maximum possible number of stones that Alice can take after making some operations.
Example
Input
3
3 4 5
1 0 5
5 3 2
Output
9
0
6
Note
For the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is 9. It is impossible to make some operations to take more than 9 stones, so the answer is 9.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | t = int(input())
while t>0:
x, y, z = [int(i) for i in input().split()]
s = 0
f = -1
z = z//2
if y >= z:
y = y - z
s = z*2 + z
else:
s = y*2 + y
f = 1
if f == -1:
y = y//2
if x >= y:
s = s + 2*y + y
else:
s = s + 2*x + x
print(s)
t-=1 | python | code_algorithm | [
{
"input": "3\n3 4 5\n1 0 5\n5 3 2\n",
"output": "9\n0\n6\n"
},
{
"input": "20\n9 4 8\n10 6 7\n4 6 0\n7 7 6\n3 3 10\n4 2 1\n4 4 0\n2 0 0\n8 8 7\n3 1 7\n3 10 7\n1 7 3\n7 9 1\n1 6 9\n0 9 5\n4 0 0\n2 10 0\n4 8 5\n10 0 1\n8 1 1\n",
"output": "12\n12\n9\n15\n9\n3\n6\n0\n15\n3\n18\n6\n12\n15\n6\n0\n6\... | code_contests | python | 0.9 | 11bd5b095c7852d588f6352f2cde64f2 |
Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the size of downloaded data per second.
The guys want to watch the whole video without any pauses, so they have to wait some integer number of seconds for a part of the video to download. After this number of seconds passes, they can start watching. Waiting for the whole video to download isn't necessary as the video can download after the guys started to watch.
Let's suppose that video's length is c seconds and Valeric and Valerko wait t seconds before the watching. Then for any moment of time t0, t β€ t0 β€ c + t, the following condition must fulfill: the size of data received in t0 seconds is not less than the size of data needed to watch t0 - t seconds of the video.
Of course, the guys want to wait as little as possible, so your task is to find the minimum integer number of seconds to wait before turning the video on. The guys must watch the video without pauses.
Input
The first line contains three space-separated integers a, b and c (1 β€ a, b, c β€ 1000, a > b). The first number (a) denotes the size of data needed to watch one second of the video. The second number (b) denotes the size of data Valeric and Valerko can download from the Net per second. The third number (c) denotes the video's length in seconds.
Output
Print a single number β the minimum integer number of seconds that Valeric and Valerko must wait to watch football without pauses.
Examples
Input
4 1 1
Output
3
Input
10 3 2
Output
5
Input
13 12 1
Output
1
Note
In the first sample video's length is 1 second and it is necessary 4 units of data for watching 1 second of video, so guys should download 4 Β· 1 = 4 units of data to watch the whole video. The most optimal way is to wait 3 seconds till 3 units of data will be downloaded and then start watching. While guys will be watching video 1 second, one unit of data will be downloaded and Valerik and Valerko will have 4 units of data by the end of watching. Also every moment till the end of video guys will have more data then necessary for watching.
In the second sample guys need 2 Β· 10 = 20 units of data, so they have to wait 5 seconds and after that they will have 20 units before the second second ends. However, if guys wait 4 seconds, they will be able to watch first second of video without pauses, but they will download 18 units of data by the end of second second and it is less then necessary.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from math import ceil
a,b,c = map(int,input().split())
t = (a*c - c*b)/b
print(ceil(t)) | python | code_algorithm | [
{
"input": "10 3 2\n",
"output": "5\n"
},
{
"input": "13 12 1\n",
"output": "1\n"
},
{
"input": "4 1 1\n",
"output": "3\n"
},
{
"input": "993 992 991\n",
"output": "1\n"
},
{
"input": "100 1 10\n",
"output": "990\n"
},
{
"input": "960 935 994\n",
"... | code_contests | python | 0.7 | a679fcb59e19003680c14ad792349658 |
The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).
You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai β€ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.
Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.
Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.
Input
The first line contains four space-separated integers x0, y0, x1, y1 (1 β€ x0, y0, x1, y1 β€ 109), denoting the initial and the final positions of the king.
The second line contains a single integer n (1 β€ n β€ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 β€ ri, ai, bi β€ 109, ai β€ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.
It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.
Output
If there is no path between the initial and final position along allowed cells, print -1.
Otherwise print a single integer β the minimum number of moves the king needs to get from the initial position to the final one.
Examples
Input
5 7 6 11
3
5 3 8
6 7 11
5 2 5
Output
4
Input
3 4 3 10
3
3 1 4
4 5 9
3 10 10
Output
6
Input
1 1 2 10
2
1 1 3
2 6 10
Output
-1
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from collections import deque
x0,y0,x1,y1=list(map(int, input().split()))
n=int(input())
allowed={}
for i in range(n):
r,a,b=list(map(int,input().split()))
for j in range(a,b+1):
allowed[(r,j)]=True
visited={}
q=deque()
q.append((x0,y0))
visited[(x0,y0)]=0
dire=[(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,1),(1,-1)]
result=-1;
while len(q)>0:
x,y=q.popleft()
original_dist=visited[(x,y)]
if x==x1 and y==y1:
result=original_dist;
break;
for i in range(len(dire)):
dx,dy=dire[i]
nx,ny=x+dx,y+dy
if (nx,ny) in allowed and (nx,ny) not in visited:
q.append((nx,ny))
visited[(nx,ny)]=original_dist+1
print(result)
| python | code_algorithm | [
{
"input": "3 4 3 10\n3\n3 1 4\n4 5 9\n3 10 10\n",
"output": "6\n"
},
{
"input": "1 1 2 10\n2\n1 1 3\n2 6 10\n",
"output": "-1\n"
},
{
"input": "5 7 6 11\n3\n5 3 8\n6 7 11\n5 2 5\n",
"output": "4\n"
},
{
"input": "1 1 1 2\n5\n1000000000 1 10000\n19920401 1188 5566\n1000000000... | code_contests | python | 1 | 712836a1862e6156852adaf7f970e8f2 |
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are n teams taking part in the national championship. The championship consists of nΒ·(n - 1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
Input
The first line contains an integer n (2 β€ n β€ 30). Each of the following n lines contains a pair of distinct space-separated integers hi, ai (1 β€ hi, ai β€ 100) β the colors of the i-th team's home and guest uniforms, respectively.
Output
In a single line print the number of games where the host team is going to play in the guest uniform.
Examples
Input
3
1 2
2 4
3 4
Output
1
Input
4
100 42
42 100
5 42
100 5
Output
5
Input
2
1 2
1 2
Output
0
Note
In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.
In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first).
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
mat=[]
for i in range(n):
mat.append(list(map(int, input().rstrip().split())))
b=0
for i in range (n):
for j in range (n):
if mat[i][0]==mat[j][1]:
b=b+1
print(b) | python | code_algorithm | [
{
"input": "2\n1 2\n1 2\n",
"output": "0\n"
},
{
"input": "4\n100 42\n42 100\n5 42\n100 5\n",
"output": "5\n"
},
{
"input": "3\n1 2\n2 4\n3 4\n",
"output": "1\n"
},
{
"input": "24\n9 83\n90 31\n83 3\n83 3\n21 31\n83 3\n32 31\n12 21\n31 21\n90 32\n32 21\n12 9\n12 31\n9 83\n83 ... | code_contests | python | 0.9 | 6856140f736c50ed7a74342275c56b8d |
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def f(x, p):
q = []
while x:
q.append(x)
x = p[x]
return q
from collections import defaultdict
n, k = map(int, input().split())
t = list(map(int, input().split()))
p = [0] * (n + 1)
for i, j in enumerate(t, 1):
p[j] = i
p = [f(i, p) for i, j in enumerate(t, 1) if j == 0]
s = defaultdict(int)
for i in p:
if k in i: t = {i.index(k) + 1}
else: s[len(i)] += 1
s = [list(range(i, k * i + 1, i)) for i, k in s.items()]
for q in s:
t |= {x + y for x in q for y in t}
print('\n'.join(map(str, sorted(list(t))))) | python | code_algorithm | [
{
"input": "6 2\n2 3 0 5 6 0\n",
"output": "2\n5\n"
},
{
"input": "6 2\n0 0 1 0 4 5\n",
"output": "1\n3\n4\n6\n"
},
{
"input": "6 1\n2 0 4 0 6 0\n",
"output": "2\n4\n6\n"
},
{
"input": "4 1\n0 0 0 0\n",
"output": "1\n2\n3\n4\n"
},
{
"input": "20 20\n0 0 0 0 0 0 0 ... | code_contests | python | 0 | 02fafef8bf2a5af20c16a627b3eaa6e9 |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
Input
The first line contains a non-empty string s β the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.
Output
Print the new sum that Xenia can count.
Examples
Input
3+2+1
Output
1+2+3
Input
1+1+3+1+3
Output
1+1+1+3+3
Input
2
Output
2
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | x=input()
x=x.replace("+","")
x=sorted(x)
for i in range(1,2*len(x)-1,2):
x.insert(i,"+")
x=''.join(x)
print(x)
| python | code_algorithm | [
{
"input": "2\n",
"output": "2\n"
},
{
"input": "3+2+1\n",
"output": "1+2+3\n"
},
{
"input": "1+1+3+1+3\n",
"output": "1+1+1+3+3\n"
},
{
"input": "2+2+1+1+3\n",
"output": "1+1+2+2+3\n"
},
{
"input": "3+1\n",
"output": "1+3\n"
},
{
"input": "1+3\n",
... | code_contests | python | 0.6 | a79dbccfed6866ed698ccd69f6cce0cc |
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 β€ i β€ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.
Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for c kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day d (1 β€ d < n), lent a barrel of honey and immediately (on day d) sell it according to a daily exchange rate. The next day (d + 1) the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day d + 1) give his friend the borrowed barrel of honey as well as c kilograms of raspberry for renting the barrel.
The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.
Input
The first line contains two space-separated integers, n and c (2 β€ n β€ 100, 0 β€ c β€ 100), β the number of days and the number of kilos of raspberry that the bear should give for borrowing the barrel.
The second line contains n space-separated integers x1, x2, ..., xn (0 β€ xi β€ 100), the price of a honey barrel on day i.
Output
Print a single integer β the answer to the problem.
Examples
Input
5 1
5 10 7 3 20
Output
3
Input
6 2
100 1 10 40 10 40
Output
97
Input
3 0
1 2 3
Output
0
Note
In the first sample the bear will lend a honey barrel at day 3 and then sell it for 7. Then the bear will buy a barrel for 3 and return it to the friend. So, the profit is (7 - 3 - 1) = 3.
In the second sample bear will lend a honey barrel at day 1 and then sell it for 100. Then the bear buy the barrel for 1 at the day 2. So, the profit is (100 - 1 - 2) = 97.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` |
n, c = map(int, input().split())
l = list(map(int, input().split()))
ans = 0
for i in range(n - 1):
d = l[i] - l[i + 1] - c
ans = max(ans, d)
print(ans) | python | code_algorithm | [
{
"input": "6 2\n100 1 10 40 10 40\n",
"output": "97\n"
},
{
"input": "5 1\n5 10 7 3 20\n",
"output": "3\n"
},
{
"input": "3 0\n1 2 3\n",
"output": "0\n"
},
{
"input": "89 1\n50 53 97 41 68 27 53 66 93 19 11 78 46 49 38 69 96 9 43 16 1 63 95 64 96 6 34 34 45 40 19 4 53 8 11 1... | code_contests | python | 0.8 | 77f77afcb1f43ea21beae7271f03f47f |
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.
But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of apples. The second line contains n integers w1, w2, ..., wn (wi = 100 or wi = 200), where wi is the weight of the i-th apple.
Output
In a single line print "YES" (without the quotes) if it is possible to divide all the apples between his friends. Otherwise print "NO" (without the quotes).
Examples
Input
3
100 200 100
Output
YES
Input
4
100 100 100 200
Output
NO
Note
In the first test sample Kitahara Haruki can give the first and the last apple to Ogiso Setsuna and the middle apple to Touma Kazusa.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
a = list(input().split(' '))
a = list(int(x) for x in a)
one, two = 0, 0
for i in range(n):
if a[i] == 100:
one += 1
else:
two += 1
flag = False
if one%2 == 0 and two%2 == 0 or one > two and two % 2 == 1 and one % 2 == 0 and one >= 2 \
or one < two and two%2 == 1 and one%2 == 0 and one >= 2:
flag = True
if not flag:
print('NO')
else:
print('YES')
| python | code_algorithm | [
{
"input": "4\n100 100 100 200\n",
"output": "NO\n"
},
{
"input": "3\n100 200 100\n",
"output": "YES\n"
},
{
"input": "9\n100 100 100 200 100 100 200 100 200\n",
"output": "YES\n"
},
{
"input": "3\n100 100 100\n",
"output": "NO\n"
},
{
"input": "7\n200 200 200 100... | code_contests | python | 0 | 314f29852d5a15fbec1cdcd15647cf04 |
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.
Your task is to write a program that can, given the number of coins each player has at the end of the game, determine the size b of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins b in the initial bet.
Input
The input consists of a single line containing five integers c1, c2, c3, c4 and c5 β the number of coins that the first, second, third, fourth and fifth players respectively have at the end of the game (0 β€ c1, c2, c3, c4, c5 β€ 100).
Output
Print the only line containing a single positive integer b β the number of coins in the initial bet of each player. If there is no such value of b, then print the only value "-1" (quotes for clarity).
Examples
Input
2 5 4 0 4
Output
3
Input
4 5 9 2 1
Output
-1
Note
In the first sample the following sequence of operations is possible:
1. One coin is passed from the fourth player to the second player;
2. One coin is passed from the fourth player to the fifth player;
3. One coin is passed from the first player to the third player;
4. One coin is passed from the fourth player to the second player.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | l=list(map(int,input().split()))
x=sum(l)
if(x%5==0 and x!=0):
print(int(x/5))
else:
print(-1)
| python | code_algorithm | [
{
"input": "2 5 4 0 4\n",
"output": "3\n"
},
{
"input": "4 5 9 2 1\n",
"output": "-1\n"
},
{
"input": "99 100 100 100 100\n",
"output": "-1\n"
},
{
"input": "57 83 11 4 93\n",
"output": "-1\n"
},
{
"input": "99 99 99 99 99\n",
"output": "99\n"
},
{
"in... | code_contests | python | 0 | 870b964652b72b721ea8c97fd7230880 |
New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 β€ i β€ n) book is wi.
As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.
1. He lifts all the books above book x.
2. He pushes book x out of the stack.
3. He puts down the lifted books without changing their order.
4. After reading book x, he puts book x on the top of the stack.
<image>
He decided to read books for m days. In the j-th (1 β€ j β€ m) day, he will read the book that is numbered with integer bj (1 β€ bj β€ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.
After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?
Input
The first line contains two space-separated integers n (2 β€ n β€ 500) and m (1 β€ m β€ 1000) β the number of books, and the number of days for which Jaehyun would read books.
The second line contains n space-separated integers w1, w2, ..., wn (1 β€ wi β€ 100) β the weight of each book.
The third line contains m space separated integers b1, b2, ..., bm (1 β€ bj β€ n) β the order of books that he would read. Note that he can read the same book more than once.
Output
Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.
Examples
Input
3 5
1 2 3
1 3 2 3 1
Output
12
Note
Here's a picture depicting the example. Each vertical column presents the stacked books.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n,m=map(int,input().split())
weight=[int(i) for i in input().split()]
order=[int(i) for i in input().split()]
stack=[]
for i in order:
if i-1 not in stack:
stack.append(i-1)
#print(stack)
ans=0
for i in order:
#i=i-1
currlift=sum(weight[i] for i in stack[0:stack.index(i-1)])
ans+=currlift
temp=i-1
stack.remove(i-1)
stack.insert(0,temp)
#print(currlift)
#print(stack)
print(ans)
| python | code_algorithm | [
{
"input": "3 5\n1 2 3\n1 3 2 3 1\n",
"output": "12\n"
},
{
"input": "50 50\n75 71 23 37 28 23 69 75 5 62 3 11 96 100 13 50 57 51 8 90 4 6 84 27 11 89 95 81 10 62 48 52 69 87 97 95 30 74 21 42 36 64 31 80 81 50 56 53 33 99\n26 30 5 33 35 29 6 15 36 17 32 16 14 1 29 34 22 40 12 42 38 48 39 50 13 47 1... | code_contests | python | 0 | 631785cd01d3f196e97c38f1c89c7e18 |
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
n=0
ans=0
while True:
i=sys.stdin.readline().strip()
if len(i)<=1:
break
if i[0]=="+":
n+=1
elif i[0]=="-":
n-=1
else:
ans+=(len(i.split(':')[1]))*n
print(ans) | python | code_algorithm | [
{
"input": "+Mike\nMike:hello\n+Kate\n+Dmitry\n-Dmitry\nKate:hi\n-Kate\n",
"output": "9\n"
},
{
"input": "+Mike\n-Mike\n+Mike\nMike:Hi I am here\n-Mike\n+Kate\n-Kate\n",
"output": "14\n"
},
{
"input": "+adabacaba\n-adabacaba\n+aca\naca:caba\n-aca\n+bacaba\n-bacaba\n+aba\n-aba\n+bad\n",... | code_contests | python | 0.7 | d40d60fad065760457d67fe7900e621e |
Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point.
Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers x, y and z to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options:
1. a1 = xyz;
2. a2 = xzy;
3. a3 = (xy)z;
4. a4 = (xz)y;
5. a5 = yxz;
6. a6 = yzx;
7. a7 = (yx)z;
8. a8 = (yz)x;
9. a9 = zxy;
10. a10 = zyx;
11. a11 = (zx)y;
12. a12 = (zy)x.
Let m be the maximum of all the ai, and c be the smallest index (from 1 to 12) such that ac = m. Rat's goal is to find that c, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that ac.
Input
The only line of the input contains three space-separated real numbers x, y and z (0.1 β€ x, y, z β€ 200.0). Each of x, y and z is given with exactly one digit after the decimal point.
Output
Find the maximum value of expression among xyz, xzy, (xy)z, (xz)y, yxz, yzx, (yx)z, (yz)x, zxy, zyx, (zx)y, (zy)x and print the corresponding expression. If there are many maximums, print the one that comes first in the list.
xyz should be outputted as x^y^z (without brackets), and (xy)z should be outputted as (x^y)^z (quotes for clarity).
Examples
Input
1.1 3.4 2.5
Output
z^y^x
Input
2.0 2.0 2.0
Output
x^y^z
Input
1.9 1.8 1.7
Output
(x^y)^z
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from decimal import *
getcontext().prec = 700
x, y, z = map(Decimal, input().split())
a = []
a.append((y**z * x.ln(), -1, 'x^y^z'))
a.append((z**y * x.ln(), -2, 'x^z^y'))
a.append((y *z * x.ln(), -3, '(x^y)^z'))
a.append((x**z * y.ln(), -5, 'y^x^z'))
a.append((z**x * y.ln(), -6, 'y^z^x'))
a.append((x *z * y.ln(), -7, '(y^x)^z'))
a.append((x**y * z.ln(), -9, 'z^x^y'))
a.append((y**x * z.ln(), -10, 'z^y^x'))
a.append((x *y * z.ln(), -11, '(z^x)^y'))
print(max(a)[2])
| python | code_algorithm | [
{
"input": "1.1 3.4 2.5\n",
"output": "z^y^x\n"
},
{
"input": "1.9 1.8 1.7\n",
"output": "(x^y)^z\n"
},
{
"input": "2.0 2.0 2.0\n",
"output": "x^y^z\n"
},
{
"input": "1.0 200.0 200.0\n",
"output": "y^z^x\n"
},
{
"input": "0.2 0.1 0.6\n",
"output": "(z^x)^y\n"
... | code_contests | python | 0 | d352bcb72cfc92d2a52cc8b9f27fca3c |
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.
There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.
There are n cars in the rental service, i-th of them is characterized with two integers ci and vi β the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.
Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.
Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
Input
The first line contains four positive integers n, k, s and t (1 β€ n β€ 2Β·105, 1 β€ k β€ 2Β·105, 2 β€ s β€ 109, 1 β€ t β€ 2Β·109) β the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.
Each of the next n lines contains two positive integers ci and vi (1 β€ ci, vi β€ 109) β the price of the i-th car and its fuel tank capacity.
The next line contains k distinct integers g1, g2, ..., gk (1 β€ gi β€ s - 1) β the positions of the gas stations on the road in arbitrary order.
Output
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
Examples
Input
3 1 8 10
10 8
5 7
11 9
3
Output
10
Input
2 2 10 18
10 4
20 6
5 3
Output
20
Note
In the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | # Question B. Road to Cinema
import sys
def roadToCinema(V, S, T, stations): # O(M)
"""
V : volume of fuel tank
S : total distance
T : time limit
stations: fuel stations' locations
rtype : boolean, whether this aircraft can travel within the time limit
"""
m = len(stations)
t = 0
stations.append(S) # destination
prev = 0
for cur in stations:
dis = cur - prev
# let Sa, Sb as the distance of accelerated mode/ normal mode respectively
# then the task is:
# min t = (Sa + 2 * Sb)
# s.t. Sa + Sb = dis
# 2 * Sa + Sb <= V
if dis > V:
# Sa <= V - dis < 0
return False
else:
# t = Sa + 2Sb = 3(Sa + Sb) - (2Sa + Sb)
# >= 3 * dis - V
# on the other hand, Sb is non-negative
# Sb = t - dis
t += max(dis * 3 - V, dis)
if t > T:
return False
prev = cur
return True
def binSearch(S, T, stations): # O(logS * M)
"""
to find the least tank volume to enable the aircraft to complete the journey
the fastest way is to complete the whole journey with the speed of 2km/min, at 2L/km
V <= 2S
"""
l = 0
r = S * 2
if T < S:
return float("inf")
while l + 1 < r:
m = l + (r - l) // 2
if roadToCinema(m, S, T, stations) == True:
r = m
else:
l = m
return r
if __name__ == "__main__": # O(logS * M + N)
line = sys.stdin.readline()
[N, M, S, T] = list(map(int, line.split(" ")))
aircrafts = []
for i in range(N):
[c, v] = list(map(int, sys.stdin.readline().split(" ")))
aircrafts.append([c, v])
stations = list(map(int, sys.stdin.readline().split(" ")))
stations.sort()
minVolume = binSearch(S, T, stations)
if minVolume == float("inf"):
# no aircraft can complete the journey
print(-1)
else:
res = float("inf")
for i in range(N):
if aircrafts[i][1] >= minVolume:
res = min(res, aircrafts[i][0])
if res == float('inf'):
# no given aircraft can complete the journey
print(-1)
else:
print(res) | python | code_algorithm | [
{
"input": "3 1 8 10\n10 8\n5 7\n11 9\n3\n",
"output": "10\n"
},
{
"input": "2 2 10 18\n10 4\n20 6\n5 3\n",
"output": "20\n"
},
{
"input": "1 1 2 2\n1000000000 1000000000\n1\n",
"output": "1000000000\n"
},
{
"input": "1 1 1000000000 1000000000\n100 1000000000\n1\n",
"outp... | code_contests | python | 0 | e39114b2595b4681b39de8ba822556e6 |
Arpa is taking a geometry exam. Here is the last problem of the exam.
You are given three points a, b, c.
Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c.
Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.
Input
The only line contains six integers ax, ay, bx, by, cx, cy (|ax|, |ay|, |bx|, |by|, |cx|, |cy| β€ 109). It's guaranteed that the points are distinct.
Output
Print "Yes" if the problem has a solution, "No" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
0 1 1 1 1 0
Output
Yes
Input
1 1 0 0 1000 1000
Output
No
Note
In the first sample test, rotate the page around (0.5, 0.5) by <image>.
In the second sample test, you can't find any solution.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | ax,ay,bx,by,cx,cy=map(int,input().split())
ab=(ax-bx)**2+(ay-by)**2
bc=(bx-cx)**2+(by-cy)**2
if ab==bc and (ay-by)*(bx-cx)!=(by-cy)*(ax-bx):
print("Yes")
else:
print("No")
| python | code_algorithm | [
{
"input": "0 1 1 1 1 0\n",
"output": "Yes\n"
},
{
"input": "1 1 0 0 1000 1000\n",
"output": "No\n"
},
{
"input": "264193194 -448876521 736684426 -633906160 -328597212 -47935734\n",
"output": "No\n"
},
{
"input": "-357531221 381512519 -761132895 -224448284 328888775 -23769256... | code_contests | python | 0 | 0c03fcbcee368ac977a7ce492572f050 |
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β three distinct two-grams.
You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of the string) maximal number of times. For example, for string s = "BBAABBBA" the answer is two-gram "BB", which contained in s three times. In other words, find any most frequent two-gram.
Note that occurrences of the two-gram can overlap with each other.
Input
The first line of the input contains integer number n (2 β€ n β€ 100) β the length of string s. The second line of the input contains the string s consisting of n capital Latin letters.
Output
Print the only line containing exactly two capital Latin letters β any two-gram contained in the given string s as a substring (i.e. two consecutive characters of the string) maximal number of times.
Examples
Input
7
ABACABA
Output
AB
Input
5
ZZZAA
Output
ZZ
Note
In the first example "BA" is also valid answer.
In the second example the only two-gram "ZZ" can be printed because it contained in the string "ZZZAA" two times.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
k = str(input())
Max = 0
for i in range(n-1):
t=k[i]+k[i+1]
z=0
for j in range(0,n-1):
s=k[j]+k[j+1]
if (s==t):
z=z+1
#print(z)
if (z>Max):
Max=z
res=t
print(res)
| python | code_algorithm | [
{
"input": "5\nZZZAA\n",
"output": "ZZ\n"
},
{
"input": "7\nABACABA\n",
"output": "AB\n"
},
{
"input": "15\nMIRZOYANOVECLOX\n",
"output": "MI\n"
},
{
"input": "23\nAABBBAAACCCCCAAADDDDDDD\n",
"output": "DD\n"
},
{
"input": "2\nQA\n",
"output": "QA\n"
},
{
... | code_contests | python | 0.8 | 34ebe58ccb7f677dc24053d7fed7d930 |
You are given an array a of n integers and an integer s. It is guaranteed that n is odd.
In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s.
The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array 6, 5, 8 is equal to 6, since if we sort this array we will get 5, 6, 8, and 6 is located on the middle position.
Input
The first line contains two integers n and s (1β€ nβ€ 2β
10^5-1, 1β€ sβ€ 10^9) β the length of the array and the required value of median.
The second line contains n integers a_1, a_2, β¦, a_n (1β€ a_i β€ 10^9) β the elements of the array a.
It is guaranteed that n is odd.
Output
In a single line output the minimum number of operations to make the median being equal to s.
Examples
Input
3 8
6 5 8
Output
2
Input
7 20
21 15 12 11 20 19 12
Output
6
Note
In the first sample, 6 can be increased twice. The array will transform to 8, 5, 8, which becomes 5, 8, 8 after sorting, hence the median is equal to 8.
In the second sample, 19 can be increased once and 15 can be increased five times. The array will become equal to 21, 20, 12, 11, 20, 20, 12. If we sort this array we get 11, 12, 12, 20, 20, 20, 21, this way the median is 20.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` |
# -*- coding: utf-8 -*-
# @Date : 2018-09-03 08:46:01
# @Author : raj lath (oorja.halt@gmail.com)
# @Link : http://codeforces.com/contest/1037/problem/B
# @Version : 1.0.0
import os
from sys import stdin
max_val=int(10e12)
min_val=int(-10e12)
def read_int() : return int(stdin.readline())
def read_ints() : return [int(x) for x in stdin.readline().split()]
def read_str() : return input()
def read_strs() : return [x for x in stdin.readline().split()]
def read_str_list(): return [x for x in stdin.readline().split().split()]
nb_elemets, value_needed = read_ints()
elements = sorted(read_ints())
mid = nb_elemets//2
ans = abs(elements[mid] - value_needed)
ans += sum( max(0, (a - value_needed)) for a in elements[:mid] )
ans += sum( max(0, (value_needed - a)) for a in elements[mid+1:] )
print(ans)
| python | code_algorithm | [
{
"input": "3 8\n6 5 8\n",
"output": "2\n"
},
{
"input": "7 20\n21 15 12 11 20 19 12\n",
"output": "6\n"
},
{
"input": "3 1\n1 2 5\n",
"output": "1\n"
},
{
"input": "1 1\n100000\n",
"output": "99999\n"
},
{
"input": "5 1\n2 2 4 6 1\n",
"output": "2\n"
},
{... | code_contests | python | 0.8 | 9b4125140c001e5e312fb9553932447c |
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.
The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters.
The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: 1, 2, 3, so that each character is painted in at most one color, and the description of the i-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color i.
The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace.
Input
The first line of the input contains two integers n, q (1 β€ n β€ 100 000, 1 β€ q β€ 1000) β the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe β a string of length n consisting of lowercase English characters.
Each of the following line describes a single evolution and is in one of the following formats:
* + i c (i β \{1, 2, 3\}, c β \{a, b, ..., z\}: append the character c to the end of i-th religion description.
* - i (i β \{1, 2, 3\}) β remove the last character from the i-th religion description. You can assume that the pattern is non-empty.
You can assume that no religion will have description longer than 250 characters.
Output
Write q lines. The i-th of them should be YES if the religions could coexist in peace after the i-th evolution, or NO otherwise.
You can print each character in any case (either upper or lower).
Examples
Input
6 8
abdabc
+ 1 a
+ 1 d
+ 2 b
+ 2 c
+ 3 a
+ 3 b
+ 1 c
- 2
Output
YES
YES
YES
YES
YES
YES
NO
YES
Input
6 8
abbaab
+ 1 a
+ 2 a
+ 3 a
+ 1 b
+ 2 b
+ 3 b
- 1
+ 2 z
Output
YES
YES
YES
YES
YES
NO
YES
NO
Note
In the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe:
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, q = map(int, input().split())
s = '!' + input()
nxt = [[n + 1] * (n + 2) for _ in range(26)]
for i in range(n - 1, -1, -1):
c = ord(s[i + 1]) - 97
for j in range(26):
nxt[j][i] = nxt[j][i + 1]
nxt[c][i] = i + 1
w = [[-1], [-1], [-1]]
idx = lambda i, j, k: i * 65536 + j * 256 + k
dp = [0] * (256 * 256 * 256)
def calc(fix=None):
r = list(map(range, (len(w[0]), len(w[1]), len(w[2]))))
if fix is not None: r[fix] = range(len(w[fix]) - 1, len(w[fix]))
for i in r[0]:
for j in r[1]:
for k in r[2]:
dp[idx(i, j, k)] = min(nxt[w[0][i]][dp[idx(i - 1, j, k)]] if i else n + 1,
nxt[w[1][j]][dp[idx(i, j - 1, k)]] if j else n + 1,
nxt[w[2][k]][dp[idx(i, j, k - 1)]] if k else n + 1)
if i == j == k == 0: dp[idx(i, j, k)] = 0
out = []
for _ in range(q):
t, *r = input().split()
if t == '+':
i, c = int(r[0]) - 1, ord(r[1]) - 97
w[i].append(c)
calc(i)
else:
i = int(r[0]) - 1
w[i].pop()
req = dp[idx(len(w[0]) - 1, len(w[1]) - 1, len(w[2]) - 1)]
out.append('YES' if req <= n else 'NO')
print(*out, sep='\n') | python | code_algorithm | [
{
"input": "6 8\nabdabc\n+ 1 a\n+ 1 d\n+ 2 b\n+ 2 c\n+ 3 a\n+ 3 b\n+ 1 c\n- 2\n",
"output": "YES\nYES\nYES\nYES\nYES\nYES\nNO\nYES\n"
},
{
"input": "6 8\nabbaab\n+ 1 a\n+ 2 a\n+ 3 a\n+ 1 b\n+ 2 b\n+ 3 b\n- 1\n+ 2 z\n",
"output": "YES\nYES\nYES\nYES\nYES\nNO\nYES\nNO\n"
},
{
"input": "1 1... | code_contests | python | 0.1 | f3c2e281794c84ed2e9de8c091552d81 |
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:
* f(0) = a;
* f(1) = b;
* f(n) = f(n-1) β f(n-2) when n > 1, where β denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
You are given three integers a, b, and n, calculate f(n).
You have to answer for T independent test cases.
Input
The input contains one or more independent test cases.
The first line of input contains a single integer T (1 β€ T β€ 10^3), the number of test cases.
Each of the T following lines contains three space-separated integers a, b, and n (0 β€ a, b, n β€ 10^9) respectively.
Output
For each test case, output f(n).
Example
Input
3
3 4 2
4 5 0
325 265 1231232
Output
7
4
76
Note
In the first example, f(2) = f(0) β f(1) = 3 β 4 = 7.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
from collections import defaultdict as dd
from collections import deque
from functools import *
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations ,product
def eprint(*args):
print(*args, file=sys.stderr)
zz=1
#sys.setrecursionlimit(10**6)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
def inc(d,c):
d[c]=d[c]+1 if c in d else 1
def bo(i):
return ord(i)-ord('A')
def li():
return [int(xx) for xx in input().split()]
def fli():
return [float(x) for x in input().split()]
def comp(a,b):
if(a>b):
return 2
return 2 if a==b else 0
def gi():
return [xx for xx in input().split()]
def fi():
return int(input())
def pro(a):
return reduce(lambda a,b:a*b,a)
def swap(a,i,j):
a[i],a[j]=a[j],a[i]
def si():
return list(input().rstrip())
def mi():
return map(int,input().split())
def gh():
sys.stdout.flush()
def isvalid(i,j):
return 0<=i<n and 0<=j<n
def bo(i):
return ord(i)-ord('a')
def graph(n,m):
for i in range(m):
x,y=mi()
a[x].append(y)
a[y].append(x)
t=fi()
while t>0:
t-=1
a,b,n=mi()
n+=1
if n%3==0:
print(a^b)
elif n%3==1:
print(a)
else:
print(b)
| python | code_algorithm | [
{
"input": "3\n3 4 2\n4 5 0\n325 265 1231232\n",
"output": "7\n4\n76\n"
},
{
"input": "10\n669924290 408119795 804030560\n663737793 250734602 29671646\n431160679 146708815 289491233\n189259304 606497663 379372476\n707829111 49504411 81710658\n54555019 65618101 626948607\n578351356 288589794 97427529... | code_contests | python | 1 | ead41a2101393248e3091fd80df4afcf |
Your math teacher gave you the following problem:
There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], β¦, [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l β€ x β€ r. The length of the segment [l; r] is equal to r - l.
Two segments [a; b] and [c; d] have a common point (intersect) if there exists x that a β€ x β€ b and c β€ x β€ d. For example, [2; 5] and [3; 10] have a common point, but [5; 6] and [1; 4] don't have.
You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given n segments.
In other words, you need to find a segment [a; b], such that [a; b] and every [l_i; r_i] have a common point for each i, and b-a is minimal.
Input
The first line contains integer number t (1 β€ t β€ 100) β the number of test cases in the input. Then t test cases follow.
The first line of each test case contains one integer n (1 β€ n β€ 10^{5}) β the number of segments. The following n lines contain segment descriptions: the i-th of them contains two integers l_i,r_i (1 β€ l_i β€ r_i β€ 10^{9}).
The sum of all values n over all the test cases in the input doesn't exceed 10^5.
Output
For each test case, output one integer β the smallest possible length of the segment which has at least one common point with all given segments.
Example
Input
4
3
4 5
5 9
7 7
5
11 19
4 17
16 16
3 12
14 17
1
1 10
1
1 1
Output
2
4
0
0
Note
In the first test case of the example, we can choose the segment [5;7] as the answer. It is the shortest segment that has at least one common point with all given segments.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | t = int(input())
for i in range(t):
n = int(input())
x = []
y = []
for i in range(n):
a, b = map(int, input().split())
x.append(a)
y.append(b)
if n == 1:
print(0)
elif min(y) > max(x):
print(0)
else:
print(abs(max(x)-min(y)))
| python | code_algorithm | [
{
"input": "4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1\n",
"output": "2\n4\n0\n0\n"
},
{
"input": "1\n2\n999999997 999999998\n999999999 1000000000\n",
"output": "1\n"
},
{
"input": "4\n1\n1 1000000000\n5\n1 1\n12 18\n1000000000 1000000000\n1 1\n8888888 88888... | code_contests | python | 0 | 081e1bb10a3a6af36f767e0dd0993de2 |
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.
Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.
There are n lamps with Spirit Tree's light. Sein knows the time of turning on and off for the i-th lamp β l_i and r_i respectively. To open the door you have to choose k lamps in such a way that there will be a moment of time when they all will be turned on.
While Sein decides which of the k lamps to pick, Ori is interested: how many ways there are to pick such k lamps that the door will open? It may happen that Sein may be wrong and there are no such k lamps. The answer might be large, so print it modulo 998 244 353.
Input
First line contains two integers n and k (1 β€ n β€ 3 β
10^5, 1 β€ k β€ n) β total number of lamps and the number of lamps that must be turned on simultaneously.
Next n lines contain two integers l_i ans r_i (1 β€ l_i β€ r_i β€ 10^9) β period of time when i-th lamp is turned on.
Output
Print one integer β the answer to the task modulo 998 244 353.
Examples
Input
7 3
1 7
3 8
4 5
6 7
1 3
5 10
8 9
Output
9
Input
3 1
1 1
2 2
3 3
Output
3
Input
3 2
1 1
2 2
3 3
Output
0
Input
3 3
1 3
2 3
3 3
Output
1
Input
5 2
1 3
2 4
3 5
4 6
5 7
Output
7
Note
In first test case there are nine sets of k lamps: (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 6), (1, 4, 6), (2, 3, 6), (2, 4, 6), (2, 6, 7).
In second test case k=1, so the answer is 3.
In third test case there are no such pairs of lamps.
In forth test case all lamps are turned on in a time 3, so the answer is 1.
In fifth test case there are seven sets of k lamps: (1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5).
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)]
def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10**19
MOD = 998244353
EPS = 10**-10
def compress(S):
zipped, unzipped = {}, {}
for i, a in enumerate(sorted(S)):
zipped[a] = i
unzipped[i] = a
return zipped, unzipped
class ModTools:
def __init__(self, MAX, MOD):
MAX += 1
self.MAX = MAX
self.MOD = MOD
factorial = [1] * MAX
factorial[0] = factorial[1] = 1
for i in range(2, MAX):
factorial[i] = factorial[i-1] * i % MOD
inverse = [1] * MAX
inverse[MAX-1] = pow(factorial[MAX-1], MOD-2, MOD)
for i in range(MAX-2, -1, -1):
inverse[i] = inverse[i+1] * (i+1) % MOD
self.fact = factorial
self.inv = inverse
def nCr(self, n, r):
if n < r: return 0
r = min(r, n-r)
numerator = self.fact[n]
denominator = self.inv[r] * self.inv[n-r] % self.MOD
return numerator * denominator % self.MOD
N, K = MAP()
LR = []
S = set()
for i in range(N):
l, r = MAP()
r += 1
LR.append((l, r))
S.add(l)
S.add(r)
zipped, _ = compress(S)
M = len(zipped)
lcnt = [0] * M
rcnt = [0] * M
for i in range(N):
LR[i] = (zipped[LR[i][0]], zipped[LR[i][1]])
lcnt[LR[i][0]] += 1
rcnt[LR[i][1]] += 1
cur = 0
ans = 0
mt = ModTools(N, MOD)
for i in range(M):
cur -= rcnt[i]
while lcnt[i]:
if cur >= K-1:
ans += mt.nCr(cur, K-1)
ans %= MOD
cur += 1
lcnt[i] -= 1
print(ans)
| python | code_algorithm | [
{
"input": "3 3\n1 3\n2 3\n3 3\n",
"output": "1\n"
},
{
"input": "3 1\n1 1\n2 2\n3 3\n",
"output": "3\n"
},
{
"input": "7 3\n1 7\n3 8\n4 5\n6 7\n1 3\n5 10\n8 9\n",
"output": "9\n"
},
{
"input": "3 2\n1 1\n2 2\n3 3\n",
"output": "0\n"
},
{
"input": "5 2\n1 3\n2 4\n... | code_contests | python | 0 | 7a00a6a5817a072c86bce014cef6676d |
In some country live wizards. They love playing with numbers.
The blackboard has two numbers written on it β a and b. The order of the numbers is not important. Let's consider a β€ b for the sake of definiteness. The players can cast one of the two spells in turns:
* Replace b with b - ak. Number k can be chosen by the player, considering the limitations that k > 0 and b - ak β₯ 0. Number k is chosen independently each time an active player casts a spell.
* Replace b with b mod a.
If a > b, similar moves are possible.
If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses.
To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second.
Input
The first line contains a single integer t β the number of input data sets (1 β€ t β€ 104). Each of the next t lines contains two integers a, b (0 β€ a, b β€ 1018). The numbers are separated by a space.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output
For any of the t input sets print "First" (without the quotes) if the player who moves first wins. Print "Second" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input.
Examples
Input
4
10 21
31 10
0 1
10 30
Output
First
Second
Second
First
Note
In the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win.
In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win.
In the third sample, the first player has no moves.
In the fourth sample, the first player wins in one move, taking 30 modulo 10.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def solve(a, b):
if a == 0:
return False
if solve(b % a, a):
b //= a
return not (b % (a + 1) & 1)
return True
n = int(input())
for _ in range(n):
a, b = [int(x) for x in input().split()]
if a > b:
a, b = b, a
if solve(a, b):
print("First")
else:
print("Second")
| python | code_algorithm | [
{
"input": "4\n10 21\n31 10\n0 1\n10 30\n",
"output": "First\nSecond\nSecond\nFirst\n"
},
{
"input": "7\n576460752303423487 2\n82 9\n101 104\n10 21\n31 10\n0 1\n10 30\n",
"output": "First\nSecond\nSecond\nFirst\nSecond\nSecond\nFirst\n"
},
{
"input": "1\n128817972817282999 32767241099463... | code_contests | python | 0 | 5e1110e6b5aed3daded7947d4dae6986 |
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.
But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find the maximum possible least common multiple of these three integers?
Input
The first line contains an integer n (1 β€ n β€ 106) β the n mentioned in the statement.
Output
Print a single integer β the maximum possible LCM of three not necessarily distinct positive integers that are not greater than n.
Examples
Input
9
Output
504
Input
7
Output
210
Note
The least common multiple of some positive integers is the least positive integer which is multiple for each of them.
The result may become very large, 32-bit integer won't be enough. So using 64-bit integers is recommended.
For the last example, we can chose numbers 7, 6, 5 and the LCM of them is 7Β·6Β·5 = 210. It is the maximum value we can get.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys, math
input = sys.stdin.readline
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
import collections as col
import math
def solve():
N = getInt()
if N == 1:
return 1
if N == 2:
return 2
if N % 2 == 1:
return N*(N-1)*(N-2)
return max(N*(N-1)*(N-2)//2,(N-1)*(N-2)*(N-3), N*(N-1)*(N-3) if N % 3 > 0 else 0)
#can we make a bigger number using N? N*(N-1), we can't use (N-2), we could use N-3
print(solve())
| python | code_algorithm | [
{
"input": "7\n",
"output": "210\n"
},
{
"input": "9\n",
"output": "504\n"
},
{
"input": "447244\n",
"output": "89460162932862372\n"
},
{
"input": "958507\n",
"output": "880611813728059710\n"
},
{
"input": "816923\n",
"output": "545182335484592526\n"
},
{
... | code_contests | python | 0.2 | 1fb05147342d93ed108355cdf76a271b |
Polycarpus is sure that his life fits the description: "first there is a white stripe, then a black one, then a white one again". So, Polycarpus is sure that this rule is going to fulfill during the next n days. Polycarpus knows that he is in for w good events and b not-so-good events. At least one event is going to take place during each day. As each day is unequivocally characterizes as a part of a white or a black stripe, then each day is going to have events of the same type only (ether good or not-so-good).
What is the number of distinct ways this scenario can develop over the next n days if Polycarpus is in for a white stripe (a stripe that has good events only, the stripe's length is at least 1 day), the a black stripe (a stripe that has not-so-good events only, the stripe's length is at least 1 day) and a white stripe again (a stripe that has good events only, the stripe's length is at least 1 day). Each of n days will belong to one of the three stripes only.
Note that even the events of the same type are distinct from each other. Even if some events occur on the same day, they go in some order (there are no simultaneous events).
Write a code that prints the number of possible configurations to sort the events into days. See the samples for clarifications on which scenarios should be considered distinct. Print the answer modulo 1000000009 (109 + 9).
Input
The single line of the input contains integers n, w and b (3 β€ n β€ 4000, 2 β€ w β€ 4000, 1 β€ b β€ 4000) β the number of days, the number of good events and the number of not-so-good events. It is guaranteed that w + b β₯ n.
Output
Print the required number of ways modulo 1000000009 (109 + 9).
Examples
Input
3 2 1
Output
2
Input
4 2 2
Output
4
Input
3 2 2
Output
4
Note
We'll represent the good events by numbers starting from 1 and the not-so-good events β by letters starting from 'a'. Vertical lines separate days.
In the first sample the possible ways are: "1|a|2" and "2|a|1". In the second sample the possible ways are: "1|a|b|2", "2|a|b|1", "1|b|a|2" and "2|b|a|1". In the third sample the possible ways are: "1|ab|2", "2|ab|1", "1|ba|2" and "2|ba|1".
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
MOD = int(1e9) + 9
def inv(n):
return pow(n, MOD - 2, MOD)
def combo(n):
rv = [0 for __ in range(n + 1)]
rv[0] = 1
for k in range(n):
rv[k + 1] = rv[k] * (n - k) % MOD * inv(k + 1) % MOD
return rv
with sys.stdin as fin, sys.stdout as fout:
n, w, b = map(int, next(fin).split())
combw = combo(w - 1)
combb = combo(b - 1)
ans = 0
for black in range(max(1, n - w), min(n - 2, b) + 1):
ans = (ans + (n - 1 - black) * combw[n - black - 1] % MOD * combb[black - 1]) % MOD
for f in w, b:
for k in range(1, f + 1):
ans = k * ans % MOD
print(ans, file=fout)
| python | code_algorithm | [
{
"input": "3 2 1\n",
"output": "2\n"
},
{
"input": "3 2 2\n",
"output": "4\n"
},
{
"input": "4 2 2\n",
"output": "4\n"
},
{
"input": "3 3 1\n",
"output": "12\n"
},
{
"input": "300 2 300\n",
"output": "775907030\n"
},
{
"input": "4000 4000 1\n",
"o... | code_contests | python | 0 | b88ed47235cb6bc5d32717d52efca784 |
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation:
<image>
A swap operation is the following sequence of actions:
* choose two indexes i, j (i β j);
* perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp.
What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?
Input
The first line contains two integers n and k (1 β€ n β€ 200; 1 β€ k β€ 10). The next line contains n integers a[1], a[2], ..., a[n] ( - 1000 β€ a[i] β€ 1000).
Output
In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations.
Examples
Input
10 2
10 -1 2 2 2 2 2 2 -1 10
Output
32
Input
5 10
-1 -1 -1 -1 -1
Output
-1
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #!/usr/local/bin/python3
n, k = map(int, input().split())
a = list(map(int, input().split()))
r_sum = a[0]
for l in range(n):
for r in range(l, n):
inside = sorted(a[l:r+1])
outside = sorted(a[:l] + a[r+1:], reverse=True)
t_sum = sum(inside)
for i in range(min(k, len(inside), len(outside))):
if outside[i] > inside[i]:
t_sum += (outside[i] - inside[i])
else:
break
if t_sum > r_sum:
r_sum = t_sum
print(r_sum)
| python | code_algorithm | [
{
"input": "5 10\n-1 -1 -1 -1 -1\n",
"output": "-1\n"
},
{
"input": "10 2\n10 -1 2 2 2 2 2 2 -1 10\n",
"output": "32\n"
},
{
"input": "1 10\n1\n",
"output": "1\n"
},
{
"input": "10 1\n-1 1 1 1 1 1 1 1 1 1\n",
"output": "9\n"
},
{
"input": "78 8\n-230 -757 673 -284... | code_contests | python | 0 | 4e28af37251e287e92d4187c7dcc5496 |
Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 β€ i1 < i2 < ... < ik β€ n) a group of size k.
Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 β€ k β€ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers.
Input
The first line contains a single integer n (1 β€ n β€ 106). The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 106).
Output
Output a single integer representing the number of required groups modulo 1000000007 (109 + 7).
Examples
Input
3
2 3 3
Output
0
Input
4
0 1 2 3
Output
10
Input
6
5 2 0 5 2 1
Output
53
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2*10**5+10)
write = lambda x: sys.stdout.write(x+"\n")
debug = lambda x: sys.stderr.write(x+"\n")
writef = lambda x: print("{:.12f}".format(x))
# zeta mebius
def zeta_super(val, n):
# len(val)==2^n
out = val[:]
for i in range(n):
for j in range(1<<n):
if not j>>i&1:
out[j] += out[j^(1<<i)]
return out
n = int(input())
a = list(map(int, input().split()))
m = max(a).bit_length()
M = 10**9+7
v = [0]*(1<<m)
for item in a:
v[item] += 1
v2 = [1]
for i in range(n+1):
v2.append(v2[-1]*2%M)
nv = zeta_super(v, m)
ans = 0
for b in range(1<<m):
ans += (v2[nv[b]]-1)*pow(-1, bin(b).count("1"))
ans %= M
print(ans%M) | python | code_algorithm | [
{
"input": "3\n2 3 3\n",
"output": "0\n"
},
{
"input": "4\n0 1 2 3\n",
"output": "10\n"
},
{
"input": "6\n5 2 0 5 2 1\n",
"output": "53\n"
},
{
"input": "2\n1 31\n",
"output": "0\n"
},
{
"input": "2\n1 0\n",
"output": "2\n"
},
{
"input": "10\n450661 12... | code_contests | python | 0 | 57537d17a127580feeea040c3aeb98c4 |
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful.
Below there was also written that a string is called beautiful if for each i (1 β€ i β€ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters.
Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.
Input
The first line of the input contains a string s (1 β€ |s| β€ 105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.
Output
If there is no way of replacing '#' characters which leads to a beautiful string print - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with.
If there are several possible answers, you may output any of them.
Examples
Input
(((#)((#)
Output
1
2
Input
()((#((#(#()
Output
2
2
1
Input
#
Output
-1
Input
(#)
Output
-1
Note
|s| denotes the length of the string s.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #!/usr/bin/env python3
s = input()
count = 0
res = []
last = s.rfind("#")
for i, c in enumerate(s):
if c == '(':
count += 1
elif c == ')':
count -= 1
else:
if i < last:
res.append(1)
count -= 1
else:
num = max(1, 1 + s.count("(") - s.count("#") - s.count(")"))
res.append(num)
count -= num
if count < 0:
res = []
print(-1)
break
for i in res:
print(i)
| python | code_algorithm | [
{
"input": "(((#)((#)\n",
"output": "1\n2\n"
},
{
"input": "#\n",
"output": "-1\n"
},
{
"input": "()((#((#(#()\n",
"output": "1\n1\n3\n"
},
{
"input": "(#)\n",
"output": "-1\n"
},
{
"input": "#(#(#((##((()))(((#)(#()#(((()()(()#(##(((()(((()))#(((((()(((((((()#((#... | code_contests | python | 0 | e6f6a82197f0cbe529b2ba93244ed8aa |
You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n.
You need to permute the array elements so that value
<image> became minimal possible. In particular, it is allowed not to change order of elements at all.
Input
The first line contains two integers n, k (2 β€ n β€ 3Β·105, 1 β€ k β€ min(5000, n - 1)).
The second line contains n integers A[1], A[2], ..., A[n] ( - 109 β€ A[i] β€ 109), separate by spaces β elements of the array A.
Output
Print the minimum possible value of the sum described in the statement.
Examples
Input
3 2
1 2 4
Output
1
Input
5 2
3 -5 3 -5 3
Output
0
Input
6 3
4 3 4 3 2 5
Output
3
Note
In the first test one of the optimal permutations is 1 4 2.
In the second test the initial order is optimal.
In the third test one of the optimal permutations is 2 3 4 4 3 5.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | f = lambda: map(int, input().split())
n, k = f()
p = sorted(f())
m, d = n // k, n % k
u, v = d + 1, k - d + 1
g = [0] * u * v
i = 0
for a in range(u):
j = a * m + a - 1
for b in range(v):
x = g[i - 1] + p[j] - p[j - m + 1] if b else 9e9
y = g[i - v] + p[j] - p[j - m] if a else 9e9
if i: g[i] = min(x, y)
i += 1
j += m
print(g[-1])
| python | code_algorithm | [
{
"input": "5 2\n3 -5 3 -5 3\n",
"output": "0\n"
},
{
"input": "3 2\n1 2 4\n",
"output": "1\n"
},
{
"input": "6 3\n4 3 4 3 2 5\n",
"output": "3\n"
},
{
"input": "30 2\n-999999924 -499999902 500000091 -999999998 500000030 -999999934 500000086 -499999918 -499999998 67 -99999996... | code_contests | python | 0 | 7a67b08d4c68ca0e1543d429ce6e913c |
Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time.
Polycarp is good at marketing, so he has already collected n requests from clients. The requests are numbered from 1 to n in order they came.
The i-th request is characterized by two values: si β the day when a client wants to start the repair of his car, di β duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on.
Polycarp is making schedule by processing requests in the order from the first to the n-th request. He schedules the i-th request as follows:
* If the car repair shop is idle for di days starting from si (si, si + 1, ..., si + di - 1), then these days are used to repair a car of the i-th client.
* Otherwise, Polycarp finds the first day x (from 1 and further) that there are di subsequent days when no repair is scheduled starting from x. In other words he chooses the smallest positive x that all days x, x + 1, ..., x + di - 1 are not scheduled for repair of any car. So, the car of the i-th client will be repaired in the range [x, x + di - 1]. It is possible that the day x when repair is scheduled to start will be less than si.
Given n requests, you are asked to help Polycarp schedule all of them according to the rules above.
Input
The first line contains integer n (1 β€ n β€ 200) β the number of requests from clients.
The following n lines contain requests, one request per line. The i-th request is given as the pair of integers si, di (1 β€ si β€ 109, 1 β€ di β€ 5Β·106), where si is the preferred time to start repairing the i-th car, di is the number of days to repair the i-th car.
The requests should be processed in the order they are given in the input.
Output
Print n lines. The i-th line should contain two integers β the start day to repair the i-th car and the finish day to repair the i-th car.
Examples
Input
3
9 2
7 3
2 4
Output
9 10
1 3
4 7
Input
4
1000000000 1000000
1000000000 1000000
100000000 1000000
1000000000 1000000
Output
1000000000 1000999999
1 1000000
100000000 100999999
1000001 2000000
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | t, p = 1, []
for i in range(int(input())):
l, d = map(int, input().split())
if t > l:
for i, q in enumerate(p, 1):
if q[0] <= l <= q[1] - d:
p.insert(i, [l + d, q[1]])
q[1] = l
break
else:
for q in p:
if q[0] <= q[1] - d:
l = q[0]
q[0] += d
break
else:
l = t
t += d
else:
p.append([t, l])
t = l + d
print(l, l + d - 1) | python | code_algorithm | [
{
"input": "4\n1000000000 1000000\n1000000000 1000000\n100000000 1000000\n1000000000 1000000\n",
"output": "1000000000 1000999999\n1 1000000\n100000000 100999999\n1000001 2000000\n"
},
{
"input": "3\n9 2\n7 3\n2 4\n",
"output": "9 10\n1 3\n4 7\n"
},
{
"input": "1\n1 5000000\n",
"outp... | code_contests | python | 0.8 | fa2e923ed627edae953d5d8a390d09e2 |
Ilya is an experienced player in tic-tac-toe on the 4 Γ 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not.
The rules of tic-tac-toe on the 4 Γ 4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal).
Input
The tic-tac-toe position is given in four lines.
Each of these lines contains four characters. Each character is '.' (empty cell), 'x' (lowercase English letter x), or 'o' (lowercase English letter o). It is guaranteed that the position is reachable playing tic-tac-toe, and it is Ilya's turn now (in particular, it means that the game is not finished). It is possible that all the cells are empty, it means that the friends left without making single turn.
Output
Print single line: "YES" in case Ilya could have won by making single turn, and "NO" otherwise.
Examples
Input
xx..
.oo.
x...
oox.
Output
YES
Input
x.ox
ox..
x.o.
oo.x
Output
NO
Input
x..x
..oo
o...
x.xo
Output
YES
Input
o.x.
o...
.x..
ooxx
Output
NO
Note
In the first example Ilya had two winning moves: to the empty cell in the left column and to the leftmost empty cell in the first row.
In the second example it wasn't possible to win by making single turn.
In the third example Ilya could have won by placing X in the last row between two existing Xs.
In the fourth example it wasn't possible to win by making single turn.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import exit
l1 = input()
l2 = input()
l3 = input()
l4 = input()
grid = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]
cross = 0
dots = []
for i in range(0, 4):
if l1[i] == ".":
dots += [[0+2, i+2]]
elif l1[i] == "x":
cross += 1
grid[0+2][i+2] = 1
if l2[i] == ".":
dots += [[1+2, i+2]]
elif l2[i] == "x":
cross += 1
grid[1+2][i+2] = 1
if l3[i] == ".":
dots += [[2+2, i+2]]
elif l3[i] == "x":
cross += 1
grid[2+2][i+2] = 1
if l4[i] == ".":
dots += [[3+2, i+2]]
elif l4[i] == "x":
cross += 1
grid[3+2][i+2] = 1
def check(dot, dir, delta):
global grid
grid[dot[0]][dot[1]] = 1
acc = 1
if dir == 0: #horizontal
for i in range(delta, delta+3):
acc *= grid[dot[0]+i][dot[1]]
elif dir == 1: #vertical
for i in range(delta, delta+3):
acc *= grid[dot[0]][dot[1]+i]
elif dir == 2: #diag1
for i in range(delta, delta+3):
acc *= grid[dot[0]+i][dot[1]+i]
elif dir == 3: #diag2
for i in range(delta, delta+3):
acc *= grid[dot[0]+i][dot[1]-i]
grid[dot[0]][dot[1]] = 0
return acc
if cross < 2 or len(dots) == 0:
print("NO")
else:
for dot in dots:
for dir in range(0, 4):
for delta in range(-2, 1):
if check(dot, dir, delta) == 1:
print("YES")
exit(0)
print("NO") | python | code_algorithm | [
{
"input": "o.x.\no...\n.x..\nooxx\n",
"output": "NO\n"
},
{
"input": "x.ox\nox..\nx.o.\noo.x\n",
"output": "NO\n"
},
{
"input": "xx..\n.oo.\nx...\noox.\n",
"output": "YES\n"
},
{
"input": "x..x\n..oo\no...\nx.xo\n",
"output": "YES\n"
},
{
"input": "xoox\n.xx.\no.... | code_contests | python | 0.2 | 33058d1f1164c23bc904e4e8a20ad093 |
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".
Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".
There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".
Sergey is very busy and asks you to help him and write the required program.
Input
The first line contains the integer n (1 β€ n β€ 100 000) β the number of letters in the word written by Stepan.
The second line contains the string s which has length that equals to n and contains only lowercase English letters β the word written by Stepan.
Output
Print the single string β the word written by Stepan converted according to the rules described in the statement.
Examples
Input
13
pobeeeedaaaaa
Output
pobeda
Input
22
iiiimpleeemeentatiioon
Output
implemeentatioon
Input
18
aeiouyaaeeiioouuyy
Output
aeiouyaeeioouy
Input
24
aaaoooiiiuuuyyyeeeggghhh
Output
aoiuyeggghhh
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
from sys import stdin, stdout
fin = stdin
fout = stdout
n = int(fin.readline().strip())
s = fin.readline().strip()
ans = []
gl = frozenset({'a', 'e', 'i', 'y', 'o', 'u'})
met = False
cdel = False
for i in range(n):
if i > 0:
if s[i] != s[i - 1]:
met = False
cdel = False
ans.append(s[i])
else:
if s[i] in gl:
if s[i] == 'e' or s[i] == 'o':
if not met:
ans.append(s[i])
elif not cdel:
ans.pop()
cdel = True
met = True
else:
ans.append(s[i])
else:
ans.append(s[i])
fout.write(''.join(ans))
| python | code_algorithm | [
{
"input": "18\naeiouyaaeeiioouuyy\n",
"output": "aeiouyaeeioouy"
},
{
"input": "22\niiiimpleeemeentatiioon\n",
"output": "implemeentatioon"
},
{
"input": "13\npobeeeedaaaaa\n",
"output": "pobeda"
},
{
"input": "24\naaaoooiiiuuuyyyeeeggghhh\n",
"output": "aoiuyeggghhh"
... | code_contests | python | 0.9 | f2a784529a71cc9bfcd5341404f359b9 |
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.
At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second β v0 + a pages, at third β v0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v1 pages per day.
Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time.
Help Mister B to calculate how many days he needed to finish the book.
Input
First and only line contains five space-separated integers: c, v0, v1, a and l (1 β€ c β€ 1000, 0 β€ l < v0 β€ v1 β€ 1000, 0 β€ a β€ 1000) β the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading.
Output
Print one integer β the number of days Mister B needed to finish the book.
Examples
Input
5 5 10 5 4
Output
1
Input
12 4 12 4 1
Output
3
Input
15 1 100 0 0
Output
15
Note
In the first sample test the book contains 5 pages, so Mister B read it right at the first day.
In the second sample test at first day Mister B read pages number 1 - 4, at second day β 4 - 11, at third day β 11 - 12 and finished the book.
In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | c,v0,v1,a,l = list(map(int, input().split(" ")))
count=1
sum=v0
while sum<c:
sum+=min(v0+count*a-l,v1-l)
count+=1
print(count) | python | code_algorithm | [
{
"input": "5 5 10 5 4\n",
"output": "1\n"
},
{
"input": "12 4 12 4 1\n",
"output": "3\n"
},
{
"input": "15 1 100 0 0\n",
"output": "15\n"
},
{
"input": "10 1 4 10 0\n",
"output": "4\n"
},
{
"input": "100 1 2 1000 0\n",
"output": "51\n"
},
{
"input": "... | code_contests | python | 0.5 | 3fef77d667a50986a5920873c6b8832a |
Polycarp takes part in a math show. He is given n tasks, each consists of k subtasks, numbered 1 through k. It takes him tj minutes to solve the j-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order.
By solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all k of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is k + 1.
Polycarp has M minutes of time. What is the maximum number of points he can earn?
Input
The first line contains three integer numbers n, k and M (1 β€ n β€ 45, 1 β€ k β€ 45, 0 β€ M β€ 2Β·109).
The second line contains k integer numbers, values tj (1 β€ tj β€ 1000000), where tj is the time in minutes required to solve j-th subtask of any task.
Output
Print the maximum amount of points Polycarp can earn in M minutes.
Examples
Input
3 4 11
1 2 3 4
Output
6
Input
5 5 10
1 2 4 8 16
Output
7
Note
In the first example Polycarp can complete the first task and spend 1 + 2 + 3 + 4 = 10 minutes. He also has the time to solve one subtask of the second task in one minute.
In the second example Polycarp can solve the first subtask of all five tasks and spend 5Β·1 = 5 minutes. Also he can solve the second subtasks of two tasks and spend 2Β·2 = 4 minutes. Thus, he earns 5 + 2 = 7 points in total.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, k, m = list(map(int, input().split()))
t = sorted(map(int, input().split()))
res = 0
for x in range(min(m//sum(t),n)+1):
rem = m - x*sum(t)
r = x*(k+1)
for i in range(k):
div = min(rem//t[i], n-x)
rem -= div*t[i]
r += div
res = max(res, r)
print(res) | python | code_algorithm | [
{
"input": "5 5 10\n1 2 4 8 16\n",
"output": "7\n"
},
{
"input": "3 4 11\n1 2 3 4\n",
"output": "6\n"
},
{
"input": "1 3 0\n6 3 4\n",
"output": "0\n"
},
{
"input": "5 4 32\n4 2 1 1\n",
"output": "21\n"
},
{
"input": "32 6 635\n3 4 2 1 7 7\n",
"output": "195\n"... | code_contests | python | 0 | 1788295961ff6f78187ea302c9d62884 |
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three.
So they play with each other according to following rules:
* Alex and Bob play the first game, and Carl is spectating;
* When the game ends, the one who lost the game becomes the spectator in the next game, and the one who was spectating plays against the winner.
Alex, Bob and Carl play in such a way that there are no draws.
Today they have played n games, and for each of these games they remember who was the winner. They decided to make up a log of games describing who won each game. But now they doubt if the information in the log is correct, and they want to know if the situation described in the log they made up was possible (that is, no game is won by someone who is spectating if Alex, Bob and Carl play according to the rules). Help them to check it!
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of games Alex, Bob and Carl played.
Then n lines follow, describing the game log. i-th line contains one integer ai (1 β€ ai β€ 3) which is equal to 1 if Alex won i-th game, to 2 if Bob won i-th game and 3 if Carl won i-th game.
Output
Print YES if the situation described in the log was possible. Otherwise print NO.
Examples
Input
3
1
1
2
Output
YES
Input
2
1
2
Output
NO
Note
In the first example the possible situation is:
1. Alex wins, Carl starts playing instead of Bob;
2. Alex wins, Bob replaces Carl;
3. Bob wins.
The situation in the second example is impossible because Bob loses the first game, so he cannot win the second one.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | num=int(input())
spectator=3
p1=1
p2=2
yes=True
for i in range(0,num):
winner=int(input())
if winner is spectator:
print("NO")
yes=False
break
if p1 is winner:
temp=spectator
spectator=p2
p2=temp
else:
temp=spectator
spectator=p1
p1=temp
if yes:
print("YES")
| python | code_algorithm | [
{
"input": "2\n1\n2\n",
"output": "NO\n"
},
{
"input": "3\n1\n1\n2\n",
"output": "YES\n"
},
{
"input": "99\n1\n3\n2\n2\n3\n1\n1\n3\n3\n3\n3\n3\n3\n1\n1\n3\n3\n3\n3\n1\n1\n3\n2\n1\n1\n1\n1\n1\n1\n1\n3\n2\n2\n2\n1\n3\n3\n1\n1\n3\n2\n1\n3\n3\n1\n2\n3\n3\n3\n1\n2\n2\n2\n3\n3\n3\n3\n3\n3\n2\n... | code_contests | python | 0.4 | 3ca8ffd72b460486dfec02ef38958088 |
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have n bacteria in the Petri dish and size of the i-th bacteria is a_i. Also you know intergalactic positive integer constant K.
The i-th bacteria can swallow the j-th bacteria if and only if a_i > a_j and a_i β€ a_j + K. The j-th bacteria disappear, but the i-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria i can swallow any bacteria j if a_i > a_j and a_i β€ a_j + K. The swallow operations go one after another.
For example, the sequence of bacteria sizes a=[101, 53, 42, 102, 101, 55, 54] and K=1. The one of possible sequences of swallows is: [101, 53, 42, 102, \underline{101}, 55, 54] β [101, \underline{53}, 42, 102, 55, 54] β [\underline{101}, 42, 102, 55, 54] β [42, 102, 55, \underline{54}] β [42, 102, 55]. In total there are 3 bacteria remained in the Petri dish.
Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.
Input
The first line contains two space separated positive integers n and K (1 β€ n β€ 2 β
10^5, 1 β€ K β€ 10^6) β number of bacteria and intergalactic constant K.
The second line contains n space separated integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^6) β sizes of bacteria you have.
Output
Print the only integer β minimal possible number of bacteria can remain.
Examples
Input
7 1
101 53 42 102 101 55 54
Output
3
Input
6 5
20 15 10 15 20 25
Output
1
Input
7 1000000
1 1 1 1 1 1 1
Output
7
Note
The first example is clarified in the problem statement.
In the second example an optimal possible sequence of swallows is: [20, 15, 10, 15, \underline{20}, 25] β [20, 15, 10, \underline{15}, 25] β [20, 15, \underline{10}, 25] β [20, \underline{15}, 25] β [\underline{20}, 25] β [25].
In the third example no bacteria can swallow any other bacteria.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, m = map(int, input().split())
l = sorted(map(int, input().split()))
t, b = l[::-1], -m
for a in l:
while b < a:
if a <= b + m:
n -= 1
b = t.pop()
print(n) | python | code_algorithm | [
{
"input": "6 5\n20 15 10 15 20 25\n",
"output": "1\n"
},
{
"input": "7 1\n101 53 42 102 101 55 54\n",
"output": "3\n"
},
{
"input": "7 1000000\n1 1 1 1 1 1 1\n",
"output": "7\n"
},
{
"input": "2 1\n1 1\n",
"output": "2\n"
},
{
"input": "4 1\n2 2 1 1\n",
"outp... | code_contests | python | 0 | 578445173ad94b5b55293f965b87316e |
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n = int(input())
cnt = [[0 for _ in range(n + 1)] for _ in range(2)]
b = [bin(_).count('1') for _ in list(map(int, input().split()))]
res = 0
suf_sum = 0
cnt[0][n] = 1
for i in range(n)[::-1]:
_sum, mx = 0, 0
lst_j = i
add = 0
for j in range(i, min(n, i + 65)):
_sum += b[j]
mx = max(mx, b[j])
if mx > _sum - mx and _sum % 2 == 0:
add -= 1
lst_j = j
suf_sum += b[i]
add += cnt[suf_sum & 1][i + 1]
res += add
cnt[0][i] = cnt[0][i + 1]
cnt[1][i] = cnt[1][i + 1]
if suf_sum & 1:
cnt[1][i] += 1
else:
cnt[0][i] += 1
print(res) | python | code_algorithm | [
{
"input": "4\n1 2 1 16\n",
"output": "4\n"
},
{
"input": "3\n6 7 14\n",
"output": "2\n"
},
{
"input": "5\n1000000000000000000 352839520853234088 175235832528365792 753467583475385837 895062156280564685\n",
"output": "3\n"
},
{
"input": "1\n15\n",
"output": "0\n"
},
{... | code_contests | python | 0 | f1e9d4d5f2555f6360641c1fbd2208ea |
Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are p players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability.
They have just finished the game and now are waiting for the result. But there's a tiny problem! The judges have lost the paper of scores! Fortunately they have calculated sum of the scores before they get lost and also for some of the players they have remembered a lower bound on how much they scored. However, the information about the bounds is private, so Hasan only got to know his bound.
According to the available data, he knows that his score is at least r and sum of the scores is s.
Thus the final state of the game can be represented in form of sequence of p integers a_1, a_2, ..., a_p (0 β€ a_i) β player's scores. Hasan is player number 1, so a_1 β₯ r. Also a_1 + a_2 + ... + a_p = s. Two states are considered different if there exists some position i such that the value of a_i differs in these states.
Once again, Hasan doesn't know the exact scores (he doesn't know his exact score as well). So he considers each of the final states to be equally probable to achieve.
Help Hasan find the probability of him winning.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q β 0, P β€ Q. Report the value of P β
Q^{-1} \pmod {998244353}.
Input
The only line contains three integers p, s and r (1 β€ p β€ 100, 0 β€ r β€ s β€ 5000) β the number of players, the sum of scores of all players and Hasan's score, respectively.
Output
Print a single integer β the probability of Hasan winning.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q β 0, P β€ Q. Report the value of P β
Q^{-1} \pmod {998244353}.
Examples
Input
2 6 3
Output
124780545
Input
5 20 11
Output
1
Input
10 30 10
Output
85932500
Note
In the first example Hasan can score 3, 4, 5 or 6 goals. If he scores 4 goals or more than he scores strictly more than his only opponent. If he scores 3 then his opponent also scores 3 and Hasan has a probability of \frac 1 2 to win the game. Thus, overall he has the probability of \frac 7 8 to win.
In the second example even Hasan's lower bound on goal implies him scoring more than any of his opponents. Thus, the resulting probability is 1.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | base=998244353;
def power(x, y):
if(y==0):
return 1
t=power(x, y//2)
t=(t*t)%base
if(y%2):
t=(t*x)%base
return t;
def inverse(x):
return power(x, base-2)
f=[1]
iv=[1]
for i in range(1, 5555):
f.append((f[i-1]*i)%base)
iv.append(inverse(f[i]))
def C(n, k):
return (f[n]*iv[k]*iv[n-k])%base
def candy(n, k):
# print(n, k)
return C(n+k-1, k-1)
def count_game(k, n, x): #k players, n points total, no player can have x point or more
if(k==0):
if(n==0):
return 1
else:
return 0
ans=0
for i in range(0, k+1):
t=n-x*i
# print(i, C(k, i))
if(t<0):
break
if(i%2):
ans=(ans-C(k, i)*candy(t, k))%base
else:
ans=(ans+C(k, i)*candy(t, k))%base
return ans
p, s, r= list(map(int, input().split()))
gamesize=count_game(p, s-r, int(1e18))
gamesize=inverse(gamesize)
ans=0;
for q in range(r, s+1):
for i in range(0, p): #exactly i people have the same score
t=s-(i+1)*q
if(t<0):
break
# print(q, i, count_game(p-i-1, t, q));
ans=(ans+C(p-1, i)*count_game(p-i-1, t, q)*gamesize*inverse(i+1))%base
print(ans)
| python | code_algorithm | [
{
"input": "10 30 10\n",
"output": "85932500\n"
},
{
"input": "2 6 3\n",
"output": "124780545\n"
},
{
"input": "5 20 11\n",
"output": "1\n"
},
{
"input": "1 5000 4999\n",
"output": "1\n"
},
{
"input": "2 1 0\n",
"output": "499122177\n"
},
{
"input": "8... | code_contests | python | 0 | a65e456f1ef25dec74b855200e2bc64a |
Polycarp has an array a consisting of n integers.
He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.
Formally:
* If it is the first move, he chooses any element and deletes it;
* If it is the second or any next move:
* if the last deleted element was odd, Polycarp chooses any even element and deletes it;
* if the last deleted element was even, Polycarp chooses any odd element and deletes it.
* If after some move Polycarp cannot make a move, the game ends.
Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.
Help Polycarp find this value.
Input
The first line of the input contains one integer n (1 β€ n β€ 2000) β the number of elements of a.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^6), where a_i is the i-th element of a.
Output
Print one integer β the minimum possible sum of non-deleted elements of the array after end of the game.
Examples
Input
5
1 5 7 8 2
Output
0
Input
6
5 1 2 4 6 3
Output
0
Input
2
1000000 1000000
Output
1000000
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
arr=list(map(int,input().split()))
arr.sort()
even=[]
odd=[]
e=0
o=0
for i in arr:
if (i%2)==0:
even=even+[i]
e=e+1
else:
odd=odd+[i]
o=o+1
if (e>o) and (e-o)>1:
print(sum(even[:(e-o-1)]))
elif (o>e) and (o-e)>1:
print(sum(odd[:(o-e-1)]))
else:
print(0)
| python | code_algorithm | [
{
"input": "2\n1000000 1000000\n",
"output": "1000000\n"
},
{
"input": "6\n5 1 2 4 6 3\n",
"output": "0\n"
},
{
"input": "5\n1 5 7 8 2\n",
"output": "0\n"
},
{
"input": "5\n1 1 1 1 1\n",
"output": "4\n"
},
{
"input": "5\n2 1 1 1 1\n",
"output": "2\n"
}
] | code_contests | python | 0 | 9e08daa2a0a67298f818aac46bd53156 |
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.
You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.
You are also given two integers 0 β€ y < x < n. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder 10^y modulo 10^x. In other words, the obtained number should have remainder 10^y when divided by 10^x.
Input
The first line of the input contains three integers n, x, y (0 β€ y < x < n β€ 2 β
10^5) β the length of the number and the integers x and y, respectively.
The second line of the input contains one decimal number consisting of n digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.
Output
Print one integer β the minimum number of operations you should perform to obtain the number having remainder 10^y modulo 10^x. In other words, the obtained number should have remainder 10^y when divided by 10^x.
Examples
Input
11 5 2
11010100101
Output
1
Input
11 5 1
11010100101
Output
3
Note
In the first example the number will be 11010100100 after performing one operation. It has remainder 100 modulo 100000.
In the second example the number will be 11010100010 after performing three operations. It has remainder 10 modulo 100000.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n,x,y = map(int,input().split())
s = input()[-x:]
if(y == 0):
num = s[:-(y+1)].count('1')
else:
num = s[:-(y+1)].count('1') + s[-y:].count('1')
if(s[-(y+1)] == "0"):
num = num + 1
print(num) | python | code_algorithm | [
{
"input": "11 5 2\n11010100101\n",
"output": "1\n"
},
{
"input": "11 5 1\n11010100101\n",
"output": "3\n"
},
{
"input": "6 4 2\n100010\n",
"output": "2\n"
},
{
"input": "4 2 1\n1000\n",
"output": "1\n"
},
{
"input": "8 5 2\n10000100\n",
"output": "0\n"
},
... | code_contests | python | 0.6 | 0fbda6c6973f4d087722fc0d0046364d |
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in a draw, both teams get d points.
The manager of the Berland capital team wants to summarize the results of the season, but, unfortunately, all information about the results of each match is lost. The manager only knows that the team has played n games and got p points for them.
You have to determine three integers x, y and z β the number of wins, draws and loses of the team. If there are multiple answers, print any of them. If there is no suitable triple (x, y, z), report about it.
Input
The first line contains four integers n, p, w and d (1 β€ n β€ 10^{12}, 0 β€ p β€ 10^{17}, 1 β€ d < w β€ 10^{5}) β the number of games, the number of points the team got, the number of points awarded for winning a match, and the number of points awarded for a draw, respectively. Note that w > d, so the number of points awarded for winning is strictly greater than the number of points awarded for draw.
Output
If there is no answer, print -1.
Otherwise print three non-negative integers x, y and z β the number of wins, draws and losses of the team. If there are multiple possible triples (x, y, z), print any of them. The numbers should meet the following conditions:
* x β
w + y β
d = p,
* x + y + z = n.
Examples
Input
30 60 3 1
Output
17 9 4
Input
10 51 5 4
Output
-1
Input
20 0 15 5
Output
0 0 20
Note
One of the possible answers in the first example β 17 wins, 9 draws and 4 losses. Then the team got 17 β
3 + 9 β
1 = 60 points in 17 + 9 + 4 = 30 games.
In the second example the maximum possible score is 10 β
5 = 50. Since p = 51, there is no answer.
In the third example the team got 0 points, so all 20 games were lost.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
from sys import argv
def extendedEuclideanAlgorithm(old_r, r):
negative = False
s, old_t = 0, 0
old_s, t = 1, 1
if (r < 0):
r = abs(r)
negative = True
while r > 0:
q = old_r // r
#MCD:
r, old_r = old_r - q * r, r
#Coeficiente s:
s, old_s = old_s - q * s, s
#Coeficiente t:
t, old_t = old_t - q * t, t
if negative:
old_t = old_t * -1
return old_r, old_s, old_t
n, p, w, d = [int(i) for i in input().split()]
mcd, s, t = extendedEuclideanAlgorithm(w, d)
if p % mcd == 0:
a1, b1, c1 = -w // mcd, d // mcd, p // mcd
x1, y1 = s * c1, t * c1
k = y1 * mcd // w
x0 = x1 + (d * k) // mcd
y0 = y1 - (w * k) // mcd
if x0 + y0 <= n and x0 >= 0 and y0 >= 0:
print(x0, y0, n - x0 - y0)
else:
print(-1)
else:
print(-1) | python | code_algorithm | [
{
"input": "30 60 3 1\n",
"output": "20 0 10\n"
},
{
"input": "20 0 15 5\n",
"output": "0 0 20\n"
},
{
"input": "10 51 5 4\n",
"output": "-1\n"
},
{
"input": "728961319347 33282698448966372 52437 42819\n",
"output": "634717821311 1235 94243496801\n"
},
{
"input": ... | code_contests | python | 0 | 366b7e5df64c01f0987bdd8decc6b07b |
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers.
LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.
Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?
Input
The first and only line contains an integer X (1 β€ X β€ 10^{12}).
Output
Print two positive integers, a and b, such that the value of max(a, b) is minimum possible and LCM(a, b) equals X. If there are several possible such pairs, you can print any.
Examples
Input
2
Output
1 2
Input
6
Output
2 3
Input
4
Output
1 4
Input
1
Output
1 1
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def LMC(a, b):
n = a * b
while a != 0 and b != 0:
if a > b:
a = a % b
else:
b = b % a
nod = a + b
nok = n // nod
return nok
from math import sqrt, ceil
n = int(input())
dividers = []
for i in range(1, ceil(sqrt(n))):
if n % i == 0:
dividers.append([i, n // i])
dividers_with_LMC = []
for el in dividers:
if LMC(el[0], el[1]) == n:
dividers_with_LMC.append(el)
if n == 1:
print('1 1')
else:
print(*dividers_with_LMC[-1]) | python | code_algorithm | [
{
"input": "1\n",
"output": "1 1\n"
},
{
"input": "4\n",
"output": "1 4\n"
},
{
"input": "6\n",
"output": "2 3\n"
},
{
"input": "2\n",
"output": "1 2\n"
},
{
"input": "205078485761\n",
"output": "185921 1103041\n"
},
{
"input": "873109054817\n",
"o... | code_contests | python | 0.2 | 9bb2088fd1bdf53d5f78466f91c0b497 |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length n, we build a graph of size n using it as follows:
* For every 1 β€ i β€ n, find the largest j such that 1 β€ j < i and p_j > p_i, and add an undirected edge between node i and node j
* For every 1 β€ i β€ n, find the smallest j such that i < j β€ n and p_j > p_i, and add an undirected edge between node i and node j
In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.
For clarity, consider as an example n = 4, and p = [3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).
A permutation p is cyclic if the graph built using p has at least one simple cycle.
Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 10^9+7.
Please refer to the Notes section for the formal definition of a simple cycle
Input
The first and only line contains a single integer n (3 β€ n β€ 10^6).
Output
Output a single integer 0 β€ x < 10^9+7, the number of cyclic permutations of length n modulo 10^9+7.
Examples
Input
4
Output
16
Input
583291
Output
135712853
Note
There are 16 cyclic permutations for n = 4. [4,2,1,3] is one such permutation, having a cycle of length four: 4 β 3 β 2 β 1 β 4.
Nodes v_1, v_2, β¦, v_k form a simple cycle if the following conditions hold:
* k β₯ 3.
* v_i β v_j for any pair of indices i and j. (1 β€ i < j β€ k)
* v_i and v_{i+1} share an edge for all i (1 β€ i < k), and v_1 and v_k share an edge.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
M = 10**9+7
fact = [1]*(n+2)
for i in range(2, n+1):
fact[i] = (i*fact[i-1])%M
print(((fact[n]-pow(2, n-1, M))+M)%M) | python | code_algorithm | [
{
"input": "4\n",
"output": "16\n"
},
{
"input": "583291\n",
"output": "135712853\n"
},
{
"input": "66\n",
"output": "257415584\n"
},
{
"input": "652615\n",
"output": "960319213\n"
},
{
"input": "482331\n",
"output": "722928541\n"
},
{
"input": "336161... | code_contests | python | 0.6 | d731152dbb21da1a61688b8d7db6de88 |
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.
Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t.
On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that.
The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct:
* n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"),
* p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 β€ k β€ min(n, m)), here characters in strings are numbered starting from 1.
Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum.
Input
The first line contains a non-empty string s (1 β€ |s| β€ 5000), where |s| is its length. The second line contains a non-empty string t (1 β€ |t| β€ 5000), where |t| is its length. Both strings consist of lowercase Latin letters.
Output
Print the sought name or -1 if it doesn't exist.
Examples
Input
aad
aac
Output
aad
Input
abad
bob
Output
daab
Input
abc
defg
Output
-1
Input
czaaab
abcdef
Output
abczaa
Note
In the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def findmin(lcopy, toexceed):
toex = ord(toexceed) - 97
for each in lcopy[(toex+1):]:
if each > 0:
return True
return False
def arrange(lcopy, toexceed = None):
if toexceed is None:
ans = ""
for i in range(26):
ans += chr(i+97)*lcopy[i]
return ans
ans = ""
for i in range(ord(toexceed)-97+1, 26):
if lcopy[i] > 0:
ans += chr(i+97)
lcopy[i] -= 1
break
return ans + arrange(lcopy)
def operation(s1, s2):
first_count = [0]*26
for letter in s1:
first_count[ord(letter)-97] += 1
common = 0
lcopy = list(first_count)
for i in range(len(s2)):
letter = s2[i]
num = ord(letter) - 97
if lcopy[num] > 0:
lcopy[num] -= 1
common += 1
else:
break
found = False
ans = ""
#print(common)
for cval in range(common, -1, -1):
#print(cval)
if cval >= len(s1):
lcopy[ord(s2[cval-1])-97] += 1
continue
else:
if cval == len(s2):
found = True
ans = s2[:cval] + arrange(lcopy)
break
else:
#print("yo", s2[cval])
if findmin(lcopy, s2[cval]):
found = True
ans = s2[:cval] + arrange(lcopy, s2[cval])
break
else:
lcopy[ord(s2[cval-1])-97] += 1
if not found:
return -1
else:
return ans
s1 = input()
s2 = input()
print(operation(s1, s2))
| python | code_algorithm | [
{
"input": "abc\ndefg\n",
"output": "-1\n"
},
{
"input": "czaaab\nabcdef\n",
"output": "abczaa\n"
},
{
"input": "aad\naac\n",
"output": "aad\n"
},
{
"input": "abad\nbob\n",
"output": "daab\n"
},
{
"input": "z\na\n",
"output": "z\n"
},
{
"input": "abc\n... | code_contests | python | 0 | 90f5cfc13cd3084cde9a471b1551f83d |
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
Input
The first line contains integer n (3 β€ n β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the i-th number in the list is the number of rounds the i-th person wants to play.
Output
In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3
3 2 2
Output
4
Input
4
2 2 2 2
Output
3
Note
You don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | # mafia
N=int(input())
a=list(map(int,input().split()))
def isok(X):
sums=0
for num in a:
if X<num:
return False
sums+=max(0,X-num)
if sums>=X:
return True
return False
l=0
r=10**12
#l -- case_impossible
#r --case_possible
while r-l>1:
m=(l+r)//2
if isok(m):
r=m
else:
l=m
print(r)
| python | code_algorithm | [
{
"input": "3\n3 2 2\n",
"output": "4\n"
},
{
"input": "4\n2 2 2 2\n",
"output": "3\n"
},
{
"input": "3\n1000000000 1000000000 10000000\n",
"output": "1005000000\n"
},
{
"input": "3\n1 2 1\n",
"output": "2\n"
},
{
"input": "3\n4 10 11\n",
"output": "13\n"
},... | code_contests | python | 0.5 | 6a77d1086f7edd900b13137b7ec52c9e |
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox, how are you going to do that?", the curious bears asked. "It's easy", said the fox. "If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal".
The little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal.
Input
The first line contains two space-separated integers a and b (1 β€ a, b β€ 109).
Output
If the fox is lying to the little bears and it is impossible to make the pieces equal, print -1. Otherwise, print the required minimum number of operations. If the pieces of the cheese are initially equal, the required number is 0.
Examples
Input
15 20
Output
3
Input
14 8
Output
-1
Input
6 6
Output
0
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from math import pow
def take_input(s): #for integer inputs
if s == 1: return int(input())
return map(int, input().split())
def factor(n,k):
i = 0
while(n%k==0):
i += 1
n //= k
return i
a, b = take_input(2)
count = 0
if a == b:
print(0)
exit()
a_fac_2 = factor(a,2); a_fac_3 = factor(a,3); a_fac_5 = factor(a,5)
b_fac_2 = factor(b,2); b_fac_3 = factor(b,3); b_fac_5 = factor(b,5)
x = a
if a_fac_2>0: x //= pow(2,a_fac_2)
if a_fac_3>0: x //= pow(3,a_fac_3)
if a_fac_5>0: x //= pow(5,a_fac_5)
y = b
if b_fac_2>0: y //= pow(2,b_fac_2)
if b_fac_3>0: y //= pow(3,b_fac_3)
if b_fac_5>0: y //= pow(5,b_fac_5)
if x != y:
print(-1)
else:
print(abs(a_fac_2 - b_fac_2) + abs(a_fac_3 - b_fac_3) + abs(a_fac_5 - b_fac_5))
| python | code_algorithm | [
{
"input": "15 20\n",
"output": "3\n"
},
{
"input": "14 8\n",
"output": "-1\n"
},
{
"input": "6 6\n",
"output": "0\n"
},
{
"input": "919536000 993098880\n",
"output": "5\n"
},
{
"input": "691200 583200\n",
"output": "8\n"
},
{
"input": "5 1000000000\n"... | code_contests | python | 0.3 | be2cccaa9a99c8cc4735c73a4d714881 |
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:
1. a1 is equivalent to b1, and a2 is equivalent to b2
2. a1 is equivalent to b2, and a2 is equivalent to b1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
Input
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
Output
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
Examples
Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO
Note
In the first sample you should split the first string into strings "aa" and "ba", the second one β into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".
In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def equals(a, b):
if (a == b):
return True
len_a, len_b = len(a), len(b)
if (len_a & 1 or len_b & 1):
return False
if (len_a == 1):
return False
as1 = a[0:len_a//2]
as2 = a[len_a//2:(len_a//2)*2]
bs1 = b[:len_b//2]
bs2 = b[len_b//2:(len_b//2)*2]
return (equals(as1, bs2) and equals(as2, bs1)) or (equals(as1, bs1) and equals(as2, bs2))
s1 = input()
s2 = input()
if (equals(s1, s2)):
print("YES")
else:
print("NO") | python | code_algorithm | [
{
"input": "aaba\nabaa\n",
"output": "YES\n"
},
{
"input": "aabb\nabab\n",
"output": "NO\n"
},
{
"input": "aabbaaaa\naaaaabab\n",
"output": "NO\n"
},
{
"input": "qgiufelsfhanx\naaaaaaaaaaaaa\n",
"output": "NO\n"
},
{
"input": "abcddd\nbacddd\n",
"output": "NO\... | code_contests | python | 0.9 | 96aa8b635b79c4c7de25e2e50ee3fffb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.