task_type
stringclasses 1
value | problem
stringlengths 209
3.39k
| answer
stringlengths 35
6.15k
| problem_tokens
int64 60
774
| answer_tokens
int64 12
2.04k
|
|---|---|---|---|---|
coding
|
Solve the programming task below in a Python markdown code block.
There are N squares aligned in a row. The i-th square from the left contains an integer a_i.
Initially, all the squares are white. Snuke will perform the following operation some number of times:
* Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares are overwritten.
After Snuke finishes performing the operation, the score will be calculated as the sum of the integers contained in the black squares. Find the maximum possible score.
Constraints
* 1≤N≤10^5
* 1≤K≤N
* a_i is an integer.
* |a_i|≤10^9
Input
The input is given from Standard Input in the following format:
N K
a_1 a_2 ... a_N
Output
Print the maximum possible score.
Examples
Input
5 3
-10 10 -10 10 -10
Output
10
Input
4 2
10 -10 -10 10
Output
20
Input
1 1
-10
Output
0
Input
10 5
5 -4 -5 -8 -4 7 2 -4 0 7
Output
17
|
{"inputs": ["1 1\n1", "1 1\n0", "1 1\n-2", "1 1\n-3", "1 1\n-9", "1 1\n-16", "1 1\n-20", "1 1\n-25"], "outputs": ["1\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
| 290
| 103
|
coding
|
Solve the programming task below in a Python markdown code block.
The alphabetized kata
---------------------
Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed!
The input is restricted to contain no numerals and only words containing the english alphabet letters.
Example:
```python
alphabetized("The Holy Bible") # "BbeehHilloTy"
```
_Inspired by [Tauba Auerbach](http://www.taubaauerbach.com/view.php?id=73)_
Also feel free to reuse/extend the following starter code:
```python
def alphabetized(s):
```
|
{"functional": "_inputs = [[''], [' '], [' a'], ['a '], [' a '], ['A b B a'], [' a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'], ['!@$%^&*()_+=-`,'], ['The Holy Bible'], [\"CodeWars can't Load Today\"]]\n_outputs = [[''], [''], ['a'], ['a'], ['a'], ['AabB'], ['aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'], [''], ['BbeehHilloTy'], ['aaaaCcdddeLnooorstTWy']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(alphabetized(*i), o[0])"}
| 153
| 335
|
coding
|
Solve the programming task below in a Python markdown code block.
The previous challenges covered Insertion Sort, which is a simple and intuitive sorting algorithm with a running time of $unrecognized$. In these next few challenges, we're covering a divide-and-conquer algorithm called Quicksort (also known as Partition Sort). This challenge is a modified version of the algorithm that only addresses partitioning. It is implemented as follows:
Step 1: Divide
Choose some pivot element, $unrecognized$, and partition your unsorted array, $unrecognized$, into three smaller arrays: $unrecognized$, $unrecognized$, and $unrecognized$, where each element in $unrecognized$, each element in $unrecognized$, and each element in $unrecognized$.
Example
$unrecognized$
In this challenge, the pivot will always be at $unrecognized$, so the pivot is $unrecognized$.
$unrecognized$ is divided into $unrecognized$, $unrecognized$, and $unrecognized$.
Putting them all together, you get $unrecognized$. There is a flexible checker that allows the elements of $unrecognized$ and $unrecognized$ to be in any order. For example, $unrecognized$ is valid as well.
Given $unrecognized$ and $unrecognized$, partition $unrecognized$ into $unrecognized$, $unrecognized$, and $unrecognized$ using the Divide instructions above. Return a 1-dimensional array containing each element in $unrecognized$ first, followed by each element in $unrecognized$, followed by each element in $unrecognized$.
Function Description
Complete the quickSort function in the editor below.
quickSort has the following parameter(s):
int arr[n]: $unrecognized$ is the pivot element
Returns
int[n]: an array of integers as described above
Input Format
The first line contains $unrecognized$, the size of $unrecognized$.
The second line contains $unrecognized$ space-separated integers $unrecognized$ (the unsorted array). The first integer, $unrecognized$, is the pivot element, $unrecognized$.
Constraints
$unrecognized$
$unrecognized$ where $unrecognized$
All elements are distinct.
Sample Input
STDIN Function
----- --------
5 arr[] size n =5
4 5 3 7 2 arr =[4, 5, 3, 7, 2]
Sample Output
3 2 4 5 7
Explanation
$unrecognized$
Pivot: $unrecognized$.
$unrecognized$; $unrecognized$; $unrecognized$
$unrecognized$, so it is added to $unrecognized$.
$unrecognized$; $unrecognized$; $unrecognized$
$unrecognized$, so it is added to $unrecognized$.
$unrecognized$; $unrecognized$; $unrecognized$
$unrecognized$, so it is added to $unrecognized$.
$unrecognized$; $unrecognized$; $unrecognized$
$unrecognized$, so it is added to $unrecognized$.
$unrecognized$; $unrecognized$; $unrecognized$
Return the array $unrecognized$.
The order of the elements to the left and right of $unrecognized$ does not need to match this answer. It is only required that $unrecognized$ and $unrecognized$ are to the left of $unrecognized$, and $unrecognized$ and $unrecognized$ are to the right.
|
{"inputs": ["5 \n4 5 3 7 2 \n"], "outputs": ["3 2 4 5 7\n"]}
| 726
| 36
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.
Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial.
Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.
Please complete the following python code precisely:
```python
class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]) == 0\n assert candidate(graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]) == 0\n assert candidate(graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]) == 1\n\n\ncheck(Solution().minMalwareSpread)"}
| 244
| 126
|
coding
|
Solve the programming task below in a Python markdown code block.
After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades.
Orpheus, a famous poet, and musician plans to calm Cerberus with his poetry and safely walk past him. He created a very peculiar poem for Cerberus. It consists only of lowercase English letters.
We call a poem's substring a palindrome if and only if it reads the same backwards and forwards. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deleting several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.
Unfortunately, Cerberus dislikes palindromes of length greater than $1$. For example in the poem abaa the hound of Hades wouldn't like substrings aba and aa.
Orpheus can only calm Cerberus if the hound likes his poetry. That's why he wants to change his poem so that it does not contain any palindrome substrings of length greater than $1$.
Orpheus can modify the poem by replacing a letter at any position with any lowercase English letter. He can use this operation arbitrarily many times (possibly zero). Since there can be many palindromes in his poem, he may have to make some corrections. But how many, exactly? Given the poem, determine the minimal number of letters that have to be changed so that the poem does not contain any palindromes of length greater than $1$.
-----Input-----
The first line of the input contains a single integer $t$ ($1 \leq t \leq 10^5$) denoting the number of test cases, then $t$ test cases follow.
The first and only line of each test case contains a non-empty string of lowercase English letters, Orpheus' poem.
The sum of the length of Orpheus' poems in all test cases will not exceed $10^5$.
-----Output-----
You should output $t$ lines, $i$-th line should contain a single integer, answer to the $i$-th test case.
-----Examples-----
Input
7
babba
abaac
codeforces
zeroorez
abcdcba
bbbbbbb
a
Output
1
1
0
1
1
4
0
-----Note-----
In the first test case, we can replace the third character with c and obtain a palindrome-less poem bacba.
In the second test case, we can replace the third character with d and obtain a palindrome-less poem abdac.
In the third test case, the initial poem already doesn't contain any palindromes, so Orpheus doesn't need to change anything there.
|
{"inputs": ["7\nbabba\nabaac\ncodeforces\nzeroorez\nabcdcba\nbbbbbbb\na\n", "7\nabbab\nabaac\ncodeforces\nzeroorez\nabcdcba\nbbbbbbb\na\n", "7\nabbab\nabaac\ncodeforces\nzeroorez\nabadcbc\nbbbbbbb\na\n", "7\nabbab\nabaac\ncodeforces\nzeroorez\nabadcbc\nbbbbabb\na\n", "7\nbbbaa\nabaac\ncodeforces\nyeroorez\nabadcbc\nbbabbbb\na\n", "7\nabcab\nabaac\ncodeforcer\nrezoorez\nabcdcba\nbbbbbbb\na\n", "7\nabcab\nabaac\ncodeforcer\nrezoorez\nabcdcba\nbbbbabb\na\n", "7\nbbbaa\nabaac\ncodeforces\nyeroorez\ndbcdaba\nbbabbbb\na\n"], "outputs": ["1\n1\n0\n1\n1\n4\n0\n", "1\n1\n0\n1\n1\n4\n0\n", "1\n1\n0\n1\n2\n4\n0\n", "1\n1\n0\n1\n2\n3\n0\n", "3\n1\n0\n1\n2\n3\n0\n", "0\n1\n0\n1\n1\n4\n0\n", "0\n1\n0\n1\n1\n3\n0\n", "3\n1\n0\n1\n1\n3\n0\n"]}
| 619
| 351
|
coding
|
Solve the programming task below in a Python markdown code block.
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not.
We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the $2$-nd pair lies inside the $1$-st one, the $3$-rd one — inside the $2$-nd one and so on. For example, nesting depth of "" is $0$, "()()()" is $1$ and "()((())())" is $3$.
Now, you are given RBS $s$ of even length $n$. You should color each bracket of $s$ into one of two colors: red or blue. Bracket sequence $r$, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets $b$, should be RBS. Any of them can be empty. You are not allowed to reorder characters in $s$, $r$ or $b$. No brackets can be left uncolored.
Among all possible variants you should choose one that minimizes maximum of $r$'s and $b$'s nesting depth. If there are multiple solutions you can print any of them.
-----Input-----
The first line contains an even integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of RBS $s$.
The second line contains regular bracket sequence $s$ ($|s| = n$, $s_i \in \{$"(", ")"$\}$).
-----Output-----
Print single string $t$ of length $n$ consisting of "0"-s and "1"-s. If $t_i$ is equal to 0 then character $s_i$ belongs to RBS $r$, otherwise $s_i$ belongs to $b$.
-----Examples-----
Input
2
()
Output
11
Input
4
(())
Output
0101
Input
10
((()())())
Output
0110001111
-----Note-----
In the first example one of optimal solutions is $s = $ "$\color{blue}{()}$". $r$ is empty and $b = $ "$()$". The answer is $\max(0, 1) = 1$.
In the second example it's optimal to make $s = $ "$\color{red}{(}\color{blue}{(}\color{red}{)}\color{blue}{)}$". $r = b = $ "$()$" and the answer is $1$.
In the third example we can make $s = $ "$\color{red}{(}\color{blue}{((}\color{red}{)()}\color{blue}{)())}$". $r = $ "$()()$" and $b = $ "$(()())$" and the answer is $2$.
|
{"inputs": ["2\n()\n", "2\n()\n", "2\n()\n", "4\n(())\n", "4\n(())\n", "4\n()()\n", "4\n(())\n", "8\n((()))()\n"], "outputs": ["00\n", "00\n", "00\n", "0110\n", "0110\n", "0000", "0110\n", "01001000\n"]}
| 692
| 116
|
coding
|
Solve the programming task below in a Python markdown code block.
Polycarp has $x$ of red and $y$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $a$ red candies and $b$ blue candies, or $a$ blue candies and $b$ red candies. Any candy can belong to at most one gift set.
Help Polycarp to find the largest number of gift sets he can create.
For example, if $x = 10$, $y = 12$, $a = 5$, and $b = 2$, then Polycarp can make three gift sets:
In the first set there will be $5$ red candies and $2$ blue candies;
In the second set there will be $5$ blue candies and $2$ red candies;
In the third set will be $5$ blue candies and $2$ red candies.
Note that in this example there is one red candy that Polycarp does not use in any gift set.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow.
Each test case consists of a single string containing four integers $x$, $y$, $a$, and $b$ ($1 \le x, y, a, b \le 10^9$).
-----Output-----
For each test case, output one number — the maximum number of gift sets that Polycarp can make.
-----Examples-----
Input
9
10 12 2 5
1 1 2 2
52 311 13 27
1000000000 1000000000 1 1
1000000000 1 1 1000000000
1 1000000000 1000000000 1
1 2 1 1
7 8 1 2
4 1 2 3
Output
3
0
4
1000000000
1
1
1
5
0
-----Note-----
None
|
{"inputs": ["9\n8 9 2 8\n0 0 2 2\n38 204 6 13\n1010010010 0000000000 6 2\n1000000000 2 1 0100001000\n1 1000100110 1000011100 1\n1 0 1 1\n6 8 2 2\n4 1 2 5\n", "9\n10 8 2 5\n1 1 2 2\n52 311 22 9\n1000000000 1000000000 1 1\n1000000000 1 1 1000000000\n1 1000000000 1000000000 1\n1 1 1 1\n7 8 1 2\n4 1 2 3\n", "9\n10 8 2 5\n1 1 2 2\n52 311 22 7\n1000000000 1000000000 1 1\n1000000000 1 1 1000000000\n1 1000000100 1000000000 1\n1 1 1 1\n7 8 1 2\n4 1 2 3\n", "9\n10 8 2 5\n1 1 2 2\n52 311 22 7\n1000000000 1000000000 2 1\n1000000000 1 1 1000000000\n1 1000000100 1000000000 1\n1 1 1 1\n7 8 1 2\n4 1 2 3\n", "9\n14 9 2 9\n1 1 2 2\n52 311 22 8\n1000000000 1000000000 2 1\n1000000000 1 1 1000000000\n1 1000000110 1000000000 1\n1 1 1 1\n7 8 1 2\n4 1 2 4\n", "9\n14 9 2 9\n1 1 2 2\n52 311 22 8\n1000000000 1000000000 2 1\n1000000000 1 1 1100000000\n1 1000000110 1000000000 1\n1 1 1 1\n7 8 1 2\n4 1 2 4\n", "9\n14 9 2 9\n1 1 2 2\n52 311 22 8\n1000000000 1000000000 4 1\n1000000000 1 1 1100000000\n1 1000000110 1000000000 1\n1 1 1 1\n7 8 1 2\n4 1 2 4\n", "9\n14 9 2 9\n1 1 2 2\n52 311 22 8\n1000000000 1000000000 5 1\n1000000000 1 1 1100000000\n1 1000000110 1000000100 1\n1 1 1 1\n7 8 1 2\n4 1 2 4\n"], "outputs": ["1\n0\n6\n0\n2\n1\n0\n3\n0\n", "2\n0\n5\n1000000000\n1\n1\n1\n5\n0\n", "2\n0\n7\n1000000000\n1\n1\n1\n5\n0\n", "2\n0\n7\n666666666\n1\n1\n1\n5\n0\n", "1\n0\n6\n666666666\n1\n1\n1\n5\n0\n", "1\n0\n6\n666666666\n0\n1\n1\n5\n0\n", "1\n0\n6\n400000000\n0\n1\n1\n5\n0\n", "1\n0\n6\n333333332\n0\n1\n1\n5\n0\n"]}
| 492
| 1,303
|
coding
|
Solve the programming task below in a Python markdown code block.
Valera is a lazy student. He has m clean bowls and k clean plates.
Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates.
When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.
Input
The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish.
Output
Print a single integer — the minimum number of times Valera will need to wash a plate/bowl.
Examples
Input
3 1 1
1 2 1
Output
1
Input
4 3 1
1 1 1 1
Output
1
Input
3 1 2
2 2 2
Output
0
Input
8 2 2
1 2 1 2 1 2 1 2
Output
4
Note
In the first sample Valera will wash a bowl only on the third day, so the answer is one.
In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.
In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.
|
{"inputs": ["1 1 1\n2\n", "1 2 1\n2\n", "1 1 2\n2\n", "1 2 2\n2\n", "1 0 1\n2\n", "1 0 0\n2\n", "1 1 0\n2\n", "1 4 1\n2\n"], "outputs": ["0", "0", "0", "0", "0\n", "1\n", "0\n", "0\n"]}
| 501
| 114
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a three-digit positive integer N.
Determine whether N is a palindromic number.
Here, a palindromic number is an integer that reads the same backward as forward in decimal notation.
-----Constraints-----
- 100≤N≤999
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
If N is a palindromic number, print Yes; otherwise, print No.
-----Sample Input-----
575
-----Sample Output-----
Yes
N=575 is also 575 when read backward, so it is a palindromic number. You should print Yes.
|
{"inputs": ["559", "676", "665", "179", "129", "371", "344", "158"], "outputs": ["No\n", "Yes\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n"]}
| 160
| 78
|
coding
|
Solve the programming task below in a Python markdown code block.
Write function ```wordsToSentence``` which will create a string from a list of strings, separated by space.
Example:
```["hello", "world"] -> "hello world"```
Also feel free to reuse/extend the following starter code:
```python
def words_to_sentence(words):
```
|
{"functional": "_inputs = [[['bacon', 'is', 'delicious']]]\n_outputs = [['bacon is delicious']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(words_to_sentence(*i), o[0])"}
| 73
| 168
|
coding
|
Solve the programming task below in a Python markdown code block.
The [half-life](https://en.wikipedia.org/wiki/Half-life) of a radioactive substance is the time it takes (on average) for one-half of its atoms to undergo radioactive decay.
# Task Overview
Given the initial quantity of a radioactive substance, the quantity remaining after a given period of time, and the period of time, return the half life of that substance.
# Usage Examples
```if:csharp
Documentation:
Kata.HalfLife Method (Double, Double, Int32)
Returns the half-life for a substance given the initial quantity, the remaining quantity, and the elasped time.
Syntax
public
static
double HalfLife(
double quantityInitial,
double quantityRemaining,
int time
)
Parameters
quantityInitial
Type: System.Double
The initial amount of the substance.
quantityRemaining
Type: System.Double
The current amount of the substance.
time
Type: System.Int32
The amount of time elapsed.
Return Value
Type: System.Double
A floating-point number representing the half-life of the substance.
```
Also feel free to reuse/extend the following starter code:
```python
def half_life(initial, remaining, time):
```
|
{"functional": "_inputs = [[10, 5, 1], [8, 4, 2], [12, 3, 2]]\n_outputs = [[1], [2], [1]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(half_life(*i), o[0])"}
| 264
| 187
|
coding
|
Solve the programming task below in a Python markdown code block.
Calculate the number of ways to color an N * M grid using K colors. Adjacent squares in the grid should have different colors. Squares are considered adjacent if they share an edge.
Input Format
The first line contains an integer T denoting the number of test-cases.
The next T lines contains integers N, M and K separated by a single space.
Output Format
Output T lines, one for each test case containing the number of ways modulo 10^{9}+7.
Constraints
1 <= T <= 10^{5}
1 <= N,M <= 8
1 <= K <= 10^{9}
Sample Input
3
3 3 2
3 4 3
1 1 1
Sample Output
2
1122
1
Explanation
For the first case, there are two ways to color the grid. The colorings are in a chessboard pattern with either color at the top right square.
Timelimits
Timelimits for this challenge can be seen here
|
{"inputs": ["3\n3 3 2\n3 4 3\n1 1 1\n"], "outputs": ["2\n1122\n1\n"]}
| 231
| 39
|
coding
|
Solve the programming task below in a Python markdown code block.
Permutation p is an ordered set of integers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1, p_2, ..., p_{n}.
Petya decided to introduce the sum operation on the set of permutations of length n. Let's assume that we are given two permutations of length n: a_1, a_2, ..., a_{n} and b_1, b_2, ..., b_{n}. Petya calls the sum of permutations a and b such permutation c of length n, where c_{i} = ((a_{i} - 1 + b_{i} - 1) mod n) + 1 (1 ≤ i ≤ n).
Operation $x \text{mod} y$ means taking the remainder after dividing number x by number y.
Obviously, not for all permutations a and b exists permutation c that is sum of a and b. That's why Petya got sad and asked you to do the following: given n, count the number of such pairs of permutations a and b of length n, that exists permutation c that is sum of a and b. The pair of permutations x, y (x ≠ y) and the pair of permutations y, x are considered distinct pairs.
As the answer can be rather large, print the remainder after dividing it by 1000000007 (10^9 + 7).
-----Input-----
The single line contains integer n (1 ≤ n ≤ 16).
-----Output-----
In the single line print a single non-negative integer — the number of such pairs of permutations a and b, that exists permutation c that is sum of a and b, modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
3
Output
18
Input
5
Output
1800
|
{"inputs": ["3\n", "5\n", "1\n", "2\n", "4\n", "6\n", "7\n", "8\n"], "outputs": ["18\n", "1800\n", "1\n", "0\n", "0\n", "0\n", "670320\n", "0\n"]}
| 455
| 79
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
Sereja have an array that consist of n integers a[1], a[2], ..., a[n]. Now Sereja want to delete some(possible none, but not all) elements from the array, such that arithmetical mean of all remaining numbers will as big as possible.
Help Sereja, find number of ways to delete numbers.
------ Input ------
First line contain integer T - number of testcases. T tests follow. First line of each testcase contain integer n. Next line contain n integers a[1], a[2], ..., a[n].
------ Output ------
For each testcase print the answer modulo 10^{9}+7.
------ Constraints ------
1 ≤ T ≤ 10
1 ≤ n ≤ 10^{5}
1 ≤ a[i] ≤ 10^{5}
------ Note ------
Test #0-1(25 points) n ≤ 20
Test #2(25 points) n ≤ 1000
Test #3-4(50 points) n ≤ 100000
----- Sample Input 1 ------
2
1
1
4
1 2 1 2
----- Sample Output 1 ------
1
3
|
{"inputs": ["2\n1\n1\n4\n1 2 1 2"], "outputs": ["1\n3"]}
| 291
| 28
|
coding
|
Solve the programming task below in a Python markdown code block.
The chef likes to play with numbers. He takes some integer number x, writes it down on his iPad, and then performs with it n−1 operations of the two kinds:
- divide the number x by 3 (x must be divisible by 3);
- multiply the number x by 2.
After each iteration, Chef writes down the result on his iPad and replaces x with the result. So there will be n numbers on the iPad after all.
You are given a sequence of length n — the numbers that Chef wrote down. This sequence is given in the order of the sequence can mismatch the order of the numbers written on the iPad.
Your problem is to rearrange elements of this sequence in such a way that it can match a possible Chef's game in the order of the numbers written on the board. I.e. each next number will be exactly two times the previous number or exactly one-third of the previous number.
I can give a guarantee that the answer exists.
-----Input:-----
- The first line of the input contains an integer number N i.e the number of the elements in the sequence.
- The second line of the input contains n integer numbers a1,a2,…, an i.e rearranged (reordered) sequence that Chef can write down on the iPad.
-----Output:-----
Print N integer numbers — rearranged (reordered) input sequence that can be the sequence that Chef could write down on the iPad.
It is guaranteed that the answer exists
-----Constraints-----
- $2 \leq N \leq 100$
- $1 \leq A[i] \leq 3* 10^{18} $
-----Sample Input:-----
6
4 8 6 3 12 9
-----Sample Output:-----
9 3 6 12 4 8
-----EXPLANATION:-----
In the first example, the given sequence can be rearranged in the following way: [9,3,6,12,4,8]. It can match possible Polycarp's game which started with x=9.
|
{"inputs": ["6\n4 8 6 3 12 9"], "outputs": ["9 3 6 12 4 8"]}
| 447
| 36
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given an integer array nums of size n.
Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.
Return the length of the longest such subarray.
The bitwise AND of an array is the bitwise AND of all the numbers in it.
A subarray is a contiguous sequence of elements within an array.
Please complete the following python code precisely:
```python
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [1,2,3,3,2,2]) == 2\n assert candidate(nums = [1,2,3,4]) == 1\n\n\ncheck(Solution().longestSubarray)"}
| 153
| 61
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a positive integer n representing the number of nodes in an undirected graph. The nodes are labeled from 1 to n.
You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected.
Divide the nodes of the graph into m groups (1-indexed) such that:
Each node in the graph belongs to exactly one group.
For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to the group with index x, and bi belongs to the group with index y, then |y - x| = 1.
Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. Return -1 if it is impossible to group the nodes with the given conditions.
Please complete the following python code precisely:
```python
class Solution:
def magnificentSets(self, n: int, edges: List[List[int]]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]) == 4\n assert candidate(n = 3, edges = [[1,2],[2,3],[3,1]]) == -1\n\n\ncheck(Solution().magnificentSets)"}
| 241
| 87
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given two integers, n and k.
An array of distinct positive integers is called a k-avoiding array if there does not exist any pair of distinct elements that sum to k.
Return the minimum possible sum of a k-avoiding array of length n.
Please complete the following python code precisely:
```python
class Solution:
def minimumSum(self, n: int, k: int) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(n = 5, k = 4) == 18\n assert candidate(n = 2, k = 6) == 3\n\n\ncheck(Solution().minimumSum)"}
| 107
| 54
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given an integer N. You have to find a [permutation] P of the integers \{1, 2, \ldots, N\} that satisfies M conditions of the following form:
(X_{i}, Y_{i}), denoting that the element X_{i}\;(1≤ X_{i} ≤ N) must appear in the prefix of length Y_{i}. Formally, if the index of the element X_{i} is K_{i} (i.e, P_{K_{i}} = X_{i}), then the condition 1≤ K_{i} ≤ Y_{i} must hold.
Print -1 if no such permutation exists. In case multiple permutations that satisfy all the conditions exist, find the lexicographically smallest one.
Note: If two arrays A and B have the same length N, then A is called lexicographically smaller than B only if there exists an index i \; (1≤ i ≤ N) such that A_{1}=B_{1}, A_{2}=B_{2}, \ldots, A_{i-1}=B_{i-1}, A_{i} < B_{i}.
------ Input Format ------
- The first line of input will contain a single integer T, denoting the number of test cases.
- The first line of each test case contains two space-separated integers N and M — the length of permutation and the number of conditions to be satisfied respectively.
- The next M lines describe the conditions. The i-th of these M lines contains two space-separated integers X_{i} and Y_{i}.
------ Output Format ------
For each test case, output a single line containing the answer:
- If no permutation satisfies the given conditions, print −1.
- Otherwise, print N space-separated integers, denoting the elements of the permutation. If there are multiple answers, output the lexicographically smallest one.
------ Constraints ------
$1 ≤ T ≤ 10^{5}$
$1 ≤ N ≤ 10^{5}$
$1 ≤ M ≤ N$
$1 ≤ X_{i}, Y_{i} ≤ N$
$X_{i} \neq X_{j}$ for each $1 ≤ i < j ≤ M$.
- The sum of $N$ over all test cases won't exceed $2\cdot 10^{5}$.
----- Sample Input 1 ------
4
3 2
2 1
1 2
4 3
1 2
4 1
3 2
4 1
2 3
5 2
5 4
3 2
----- Sample Output 1 ------
2 1 3
-1
1 2 3 4
1 3 2 5 4
----- explanation 1 ------
Test case $1$: The only permutation of length $3$ that satisfies all the conditions is $[2,1,3]$.
Test case $2$: There is no permutation of length $4$ that satisfies all the given conditions.
Test case $3$: There are many permutations of length $4$ that satisfy all the conditions, such as $[1,2,3,4],[1, 4, 2, 3],[1, 3, 2, 4], [2, 1, 4, 3], [2, 1, 3, 4]$, etc. $[1,2,3,4]$ is the lexicographically smallest among them.
|
{"inputs": ["4\n3 2\n2 1\n1 2\n4 3\n1 2\n4 1\n3 2\n4 1\n2 3\n5 2\n5 4\n3 2\n"], "outputs": ["2 1 3\n-1\n1 2 3 4\n1 3 2 5 4\n"]}
| 751
| 87
|
coding
|
Solve the programming task below in a Python markdown code block.
Problem
Given the string S, which consists of lowercase letters and numbers. Follow the steps below to compress the length of string S.
1. Change the order of the characters in the character string to any order.
Example: "0ig3he12fz99"-> "efghiz012399"
2. Perform the following operations any number of times.
* Select a contiguous substring of "abcdefghijklmnopqrstuvwxyz" in the string and replace it with (first character)'-' (last character).
Example: "efghiz012399"-> "e-iz012399"
* Select a string with a tolerance of 1 (a continuous substring of "0123456789") in the string and replace it with (first digit)'-' (last digit).
Example: "e-iz012399"-> "e-iz0-399"
Find the minimum length of the string obtained by compressing the string S.
Constraints
* 1 ≤ | S | ≤ 100
* String S contains only lowercase letters and numbers
Input
The string S is given on one line.
Output
Output the minimum value of the length of the character string obtained by compressing the character string S on one line. If it cannot be compressed, output the length of the original string S.
Examples
Input
0ig3he12fz99
Output
9
Input
1122334455
Output
6
|
{"inputs": ["2", "90", "111", "011", "010", "001", "101", "000"], "outputs": ["1\n", "2\n", "3\n", "3\n", "3\n", "3\n", "3\n", "3\n"]}
| 337
| 75
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.
Please complete the following python code precisely:
```python
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [10,20,30,5,10,50]) == 65\n assert candidate(nums = [10,20,30,40,50]) == 150\n assert candidate(nums = [12,17,15,13,10,11,12]) == 33\n assert candidate(nums = [100,10,1]) == 100\n\n\ncheck(Solution().maxAscendingSum)"}
| 140
| 128
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a string s consisting of `A`, `B` and `C`.
Snuke wants to perform the following operation on s as many times as possible:
* Choose a contiguous substring of s that reads `ABC` and replace it with `BCA`.
Find the maximum possible number of operations.
Constraints
* 1 \leq |s| \leq 200000
* Each character of s is `A`, `B` and `C`.
Input
Input is given from Standard Input in the following format:
s
Output
Find the maximum possible number of operations.
Examples
Input
ABCABC
Output
3
Input
C
Output
0
Input
ABCACCBABCBCAABCB
Output
6
|
{"inputs": ["B", "D", "E", "F", "A", "G", "H", "I"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
| 173
| 62
|
coding
|
Solve the programming task below in a Python markdown code block.
Santa has to send presents to the kids. He has a large stack of $n$ presents, numbered from $1$ to $n$; the topmost present has number $a_1$, the next present is $a_2$, and so on; the bottom present has number $a_n$. All numbers are distinct.
Santa has a list of $m$ distinct presents he has to send: $b_1$, $b_2$, ..., $b_m$. He will send them in the order they appear in the list.
To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $k$ presents above the present Santa wants to send, it takes him $2k + 1$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).
What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.
Your program has to answer $t$ different test cases.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.
Then the test cases follow, each represented by three lines.
The first line contains two integers $n$ and $m$ ($1 \le m \le n \le 10^5$) — the number of presents in the stack and the number of presents Santa wants to send, respectively.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le n$, all $a_i$ are unique) — the order of presents in the stack.
The third line contains $m$ integers $b_1$, $b_2$, ..., $b_m$ ($1 \le b_i \le n$, all $b_i$ are unique) — the ordered list of presents Santa has to send.
The sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case print one integer — the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
-----Example-----
Input
2
3 3
3 1 2
3 2 1
7 2
2 1 7 3 4 5 6
3 1
Output
5
8
|
{"inputs": ["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1\n", "2\n3 3\n3 1 2\n3 2 1\n7 2\n4 1 7 3 4 5 6\n3 1\n", "2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n6 1\n", "2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n4 1\n", "2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 5 7 6\n2 1\n", "2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 5 5 6\n1 2\n", "2\n3 3\n3 1 2\n3 2 1\n7 2\n4 1 7 3 2 5 4\n5 1\n", "2\n3 3\n3 1 2\n3 2 1\n7 2\n4 1 7 3 5 5 6\n3 1\n"], "outputs": ["5\n8\n", "5\n8\n", "5\n14\n", "5\n10\n", "5\n2\n", "5\n4\n", "5\n12\n", "5\n8\n"]}
| 611
| 393
|
coding
|
Solve the programming task below in a Python markdown code block.
Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.
String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
-----Input-----
First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s).
Second line of input contains integer k (1 ≤ k ≤ 26).
-----Output-----
Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.
-----Examples-----
Input
yandex
6
Output
0
Input
yahoo
5
Output
1
Input
google
7
Output
impossible
-----Note-----
In the first test case string contains 6 different letters, so we don't need to change anything.
In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.
In the third test case, it is impossible to make 7 different letters because the length of the string is 6.
|
{"inputs": ["a\n1\n", "z\n2\n", "a\n3\n", "a\n1\n", "z\n2\n", "a\n3\n", "y\n2\n", "b\n3\n"], "outputs": ["0\n", "impossible\n", "impossible\n", "0\n", "impossible\n", "impossible\n", "impossible\n", "impossible\n"]}
| 298
| 92
|
coding
|
Solve the programming task below in a Python markdown code block.
Serval is fighting with a monster.
The health of the monster is H.
In one attack, Serval can decrease the monster's health by A.
There is no other way to decrease the monster's health.
Serval wins when the monster's health becomes 0 or below.
Find the number of attacks Serval needs to make before winning.
-----Constraints-----
- 1 \leq H \leq 10^4
- 1 \leq A \leq 10^4
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
H A
-----Output-----
Print the number of attacks Serval needs to make before winning.
-----Sample Input-----
10 4
-----Sample Output-----
3
- After one attack, the monster's health will be 6.
- After two attacks, the monster's health will be 2.
- After three attacks, the monster's health will be -2.
Thus, Serval needs to make three attacks to win.
|
{"inputs": ["4 3", "1 1\n", "14 4", "14 3", "11 2", "14 5", "26 4", "20 2"], "outputs": ["2\n", "1\n", "4\n", "5\n", "6\n", "3\n", "7\n", "10\n"]}
| 228
| 86
|
coding
|
Solve the programming task below in a Python markdown code block.
Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a and b. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros?
For example if the equation is 101 + 102 = 203, if we removed all zeros it will be 11 + 12 = 23 which is still a correct equation.
But if the equation is 105 + 106 = 211, if we removed all zeros it will be 15 + 16 = 211 which is not a correct equation.
Input
The input will consist of two lines, the first line will contain the integer a, and the second line will contain the integer b which are in the equation as described above (1 ≤ a, b ≤ 109). There won't be any leading zeros in both. The value of c should be calculated as c = a + b.
Output
The output will be just one line, you should print "YES" if the equation will remain correct after removing all zeros, and print "NO" otherwise.
Examples
Input
101
102
Output
YES
Input
105
106
Output
NO
|
{"inputs": ["5\n4\n", "1\n1\n", "6\n4\n", "1\n6\n", "5\n1\n", "6\n3\n", "5\n2\n", "1\n10\n"], "outputs": ["YES\n", "YES\n", "NO\n", "YES\n", "YES\n", "YES\n", "YES\n", "NO\n"]}
| 339
| 87
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
The staff of one of the most famous ChefLand's restaurants have just received the news! A delegation from the neighbouring country is going to visit the restaurant. The staff want to make this visit exciting and pleasant. Lucy is also a member of the staff and among all the things that the staff want to do, her assignment is to arrange the flowers on the tables.
Generally, there are 26 kinds of flowers, a small latin letter corresponds to a single kind. Equal letters correspond to equal kinds. Different letters correspond to different kinds. According to the old ChefLand tradition, one can make a bouquet from some flowers only if it is a substring of some magic string T. ChefLands make bouquets in such a manner that the order of flowers in them is important. The restaurant has a tradition to decorate a single table with N, not necessary different, bouquets. Their order matters.
Some decorations look really similar. Generally, two arrangements (let's call them A and B) are similar if B is a cyclic shift of A, or B is a reversed cyclic shift of A. For example the sequence ("aba", "c", "b") is a cyclic shift of a sequence ("b", "aba", "c"), and the sequence ("c", "b", "a", "e", "d") is a reversed cyclic shift of a sequence ("a", "b", "c", "d", "e").
Now Lucy thinks that the most beautiful bouquets are "symmetric" ones. The bouquet is "symmetric" if the string that corresponds to the arrangement of flowers in it is a palindrome (it reads from left to right the same as from right to left).
So, she thinks that the decoration of the table will be especially beautiful if all the bouquets in it are "symmetric". But then, Lucy had realized that the number of such decorations of the tables can be less than the number of guests. She doesn't want to decorate two tables in a similar manner, so she would like to know the number of distinct decorations such that no two tables looks similar.
------ Input ------
The first line of input consists of a single string T.
The second line of input consists of a single integer N.
------ Output ------
Output the number of distinct decorations.
------ Constraints ------
1 ≤ |T| ≤ 100000;
1 ≤ N ≤ 600;
String T consists only of lowercase English letters.
------ Example ------
Input:
aba
4
Output:
21
|
{"inputs": ["aba\n4"], "outputs": ["21"]}
| 540
| 15
|
coding
|
Solve the programming task below in a Python markdown code block.
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $n$ haybale piles on the farm. The $i$-th pile contains $a_i$ haybales.
However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $i$ and $j$ ($1 \le i, j \le n$) such that $|i-j|=1$ and $a_i>0$ and apply $a_i = a_i - 1$, $a_j = a_j + 1$. She may also decide to not do anything on some days because she is lazy.
Bessie wants to maximize the number of haybales in pile $1$ (i.e. to maximize $a_1$), and she only has $d$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $1$ if she acts optimally!
-----Input-----
The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases. Next $2t$ lines contain a description of test cases — two lines per test case.
The first line of each test case contains integers $n$ and $d$ ($1 \le n,d \le 100$) — the number of haybale piles and the number of days, respectively.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 100$) — the number of haybales in each pile.
-----Output-----
For each test case, output one integer: the maximum number of haybales that may be in pile $1$ after $d$ days if Bessie acts optimally.
-----Example-----
Input
3
4 5
1 0 3 2
2 2
100 1
1 8
0
Output
3
101
0
-----Note-----
In the first test case of the sample, this is one possible way Bessie can end up with $3$ haybales in pile $1$: On day one, move a haybale from pile $3$ to pile $2$ On day two, move a haybale from pile $3$ to pile $2$ On day three, move a haybale from pile $2$ to pile $1$ On day four, move a haybale from pile $2$ to pile $1$ On day five, do nothing
In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile $2$ to pile $1$ on the second day.
|
{"inputs": ["3\n4 5\n1 0 3 2\n2 2\n100 1\n1 8\n0\n", "3\n4 5\n1 0 1 2\n2 2\n100 1\n1 8\n0\n", "3\n4 5\n1 0 1 2\n2 2\n100 2\n1 8\n0\n", "3\n4 5\n0 0 1 2\n2 2\n100 2\n1 7\n0\n", "3\n4 5\n0 0 1 2\n2 2\n000 2\n1 7\n0\n", "3\n4 5\n1 0 3 2\n2 2\n100 0\n1 8\n0\n", "3\n4 5\n2 0 1 2\n2 2\n100 2\n1 8\n0\n", "3\n4 1\n1 0 1 2\n2 2\n100 2\n1 7\n0\n"], "outputs": ["3\n101\n0\n", "3\n101\n0\n", "3\n102\n0\n", "2\n102\n0\n", "2\n2\n0\n", "3\n100\n0\n", "4\n102\n0\n", "1\n102\n0\n"]}
| 670
| 340
|
coding
|
Solve the programming task below in a Python markdown code block.
You are at your grandparents' house and you are playing an old video game on a strange console. Your controller has only two buttons and each button has a number written on it.
Initially, your score is $0$. The game is composed of $n$ rounds. For each $1\le i\le n$, the $i$-th round works as follows.
On the screen, a symbol $s_i$ appears, which is either ${+}$ (plus) or ${-}$ (minus). Then you must press one of the two buttons on the controller once. Suppose you press a button with the number $x$ written on it: your score will increase by $x$ if the symbol was ${+}$ and will decrease by $x$ if the symbol was ${-}$. After you press the button, the round ends.
After you have played all $n$ rounds, you win if your score is $0$.
Over the years, your grandparents bought many different controllers, so you have $q$ of them. The two buttons on the $j$-th controller have the numbers $a_j$ and $b_j$ written on them. For each controller, you must compute whether you can win the game playing with that controller.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 2\cdot 10^5$) — the number of rounds.
The second line contains a string $s$ of length $n$ — where $s_i$ is the symbol that will appear on the screen in the $i$-th round. It is guaranteed that $s$ contains only the characters ${+}$ and ${-}$.
The third line contains an integer $q$ ($1 \le q \le 10^5$) — the number of controllers.
The following $q$ lines contain two integers $a_j$ and $b_j$ each ($1 \le a_j, b_j \le 10^9$) — the numbers on the buttons of controller $j$.
-----Output-----
Output $q$ lines. On line $j$ print ${YES}$ if the game is winnable using controller $j$, otherwise print ${NO}$.
-----Examples-----
Input
8
+-+---+-
5
2 1
10 3
7 9
10 10
5 3
Output
YES
NO
NO
NO
YES
Input
6
+-++--
2
9 7
1 1
Output
YES
YES
Input
20
+-----+--+--------+-
2
1000000000 99999997
250000000 1000000000
Output
NO
YES
-----Note-----
In the first sample, one possible way to get score $0$ using the first controller is by pressing the button with numnber $1$ in rounds $1$, $2$, $4$, $5$, $6$ and $8$, and pressing the button with number $2$ in rounds $3$ and $7$. It is possible to show that there is no way to get a score of $0$ using the second controller.
|
{"inputs": ["6\n+-++--\n2\n9 7\n1 1\n", "1\n-\n1\n427470105 744658699\n", "8\n+-+---+-\n5\n2 1\n10 3\n7 9\n10 10\n5 3\n", "20\n+-----+--+--------+-\n2\n1000000000 99999997\n250000000 1000000000\n"], "outputs": ["YES\nYES\n", "NO\n", "YES\nNO\nNO\nNO\nYES\n", "NO\nYES\n"]}
| 706
| 172
|
coding
|
Solve the programming task below in a Python markdown code block.
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $n$ students doing yet another trick.
Let's assume that all these students are numbered from $1$ to $n$. The teacher came to student $a$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $p_a$.
After that, the teacher came to student $p_a$ and made a hole in his badge as well. The student in reply said that the main culprit was student $p_{p_a}$.
This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.
After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.
You don't know the first student who was caught by the teacher. However, you know all the numbers $p_i$. Your task is to find out for every student $a$, who would be the student with two holes in the badge if the first caught student was $a$.
-----Input-----
The first line of the input contains the only integer $n$ ($1 \le n \le 1000$) — the number of the naughty students.
The second line contains $n$ integers $p_1$, ..., $p_n$ ($1 \le p_i \le n$), where $p_i$ indicates the student who was reported to the teacher by student $i$.
-----Output-----
For every student $a$ from $1$ to $n$ print which student would receive two holes in the badge, if $a$ was the first student caught by the teacher.
-----Examples-----
Input
3
2 3 2
Output
2 2 3
Input
3
1 2 3
Output
1 2 3
-----Note-----
The picture corresponds to the first example test case.
$8$
When $a = 1$, the teacher comes to students $1$, $2$, $3$, $2$, in this order, and the student $2$ is the one who receives a second hole in his badge.
When $a = 2$, the teacher comes to students $2$, $3$, $2$, and the student $2$ gets a second hole in his badge. When $a = 3$, the teacher will visit students $3$, $2$, $3$ with student $3$ getting a second hole in his badge.
For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
|
{"inputs": ["1\n1\n", "1\n1\n", "2\n2 1\n", "2\n2 1\n", "3\n2 3 2\n", "3\n1 2 3\n", "3\n2 3 1\n", "3\n2 3 1\n"], "outputs": ["1 \n", "1\n", "1 2 \n", "1 2\n", "2 2 3 \n", "1 2 3 \n", "1 2 3 \n", "1 2 3\n"]}
| 603
| 131
|
coding
|
Solve the programming task below in a Python markdown code block.
There are 3N participants in AtCoder Group Contest. The strength of the i-th participant is represented by an integer a_i. They will form N teams, each consisting of three participants. No participant may belong to multiple teams.
The strength of a team is defined as the second largest strength among its members. For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.
Find the maximum possible sum of the strengths of N teams.
Constraints
* 1 ≤ N ≤ 10^5
* 1 ≤ a_i ≤ 10^{9}
* a_i are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N}
Output
Print the answer.
Examples
Input
2
5 2 8 5 1 5
Output
10
Input
10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000
Output
10000000000
|
{"inputs": ["2\n2 2 8 5 1 5", "2\n0 4 8 5 1 5", "2\n0 7 8 5 1 5", "2\n0 7 8 9 1 5", "2\n1 4 8 9 1 2", "2\n1 4 8 4 1 2", "2\n5 2 8 5 1 5", "2\n0 4 10 4 1 0"], "outputs": ["7\n", "9\n", "12\n", "13\n", "10\n", "6\n", "10", "5\n"]}
| 570
| 162
|
coding
|
Solve the programming task below in a Python markdown code block.
General primality test are often computationally expensive, so in the biggest prime number race the idea is to study special sub-families of prime number and develop more effective tests for them.
[Mersenne Primes](https://en.wikipedia.org/wiki/Mersenne_prime) are prime numbers of the form: Mn = 2^(n) - 1. So far, 49 of them was found between M2 (3) and M74,207,281 which contains 22,338,618 digits and is (by September 2015) the biggest known prime. It has been found by GIMPS (Great Internet Mersenne Prime Search), wich use the test srudied here. (plus heuristics mentionned below)
Lucas and Lehmer have developed a [simple test](https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test) for Mersenne primes:
> for `p` (an odd prime), the Mersenne number Mp is prime if and only if `S(p − 1) = 0 mod Mp`,
>where `S(n + 1) = S(n) * S(n) − 2` and `S(1) = 4`
The goal of this kata is to implement this test. Given an integer `>=2`, the program should calculate the sequence `S(n)` up to `p-1` and calculate the remainder modulo `Mp`, then return `True` or `False` as a result of the test. The case `n = 2` should return `True`.
You should take advantage of the fact that:
```k = (k mod 2^n + floor(k/2^n)) mod Mn```
Or in other words, if we take the least significant `n` bits of `k`, and add the remaining bits of `k`, and then do this repeatedly until at most `n` bits remain, we can compute the remainder after dividing `k` by the Mersenne number `2^n−1` without using division.
This test can be improved using the fact that if `n` is not prime, `2^n-1` will not be prime. So in theory you can test for the primality of `n` beforehand. But in practice the test for the primality of `n` will rapidly outgrow in difficulty the Lucas-Lehmer test. So we can only use heuristics to rule out `n` with small factors but not complete factorization algorithm. You don't need to implement such heuristics here.
The rapid growth of `s^2` makes javascript reach its integer limit quickly (coherent result for `n = 13`, but not `17`). Whereas python seems to be only limited by the execution time limit and let us see that M11,213 is prime (contains 3376 digits).
Also feel free to reuse/extend the following starter code:
```python
def lucas_lehmer(n):
```
|
{"functional": "_inputs = [[2], [3], [4], [5], [7], [10], [33], [101], [11213], [11215]]\n_outputs = [[True], [True], [False], [True], [True], [False], [False], [False], [True], [False]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(lucas_lehmer(*i), o[0])"}
| 657
| 223
|
coding
|
Solve the programming task below in a Python markdown code block.
Things are heated up between the Finance team and the Marketing team, and they decide to have one-on-one fifa matches to settle it once and for all.
Jha, being an intern, won’t play (it’s a battle of legends, after all) and has been given one job: to fix matches in the "hope" that he’ll match players of similar skill levels (so that matches aren’t one way and everybody enjoys).
He, being on Finance team, wants his team to win (disregarding ethics). Each game carries 100 points which is awarded to the winner or divided (50-50) between the players if it ends in a draw (according to skill levels of the players).
Jha has pulled off an all-nighter to come up with the best assignment possible. But he’s way too tired now. Help him verify his answer by calculating the maximum possible score of Finance team so that he can either sleep peacefully or come up with a new assignment if he missed the optimal one.
Input Format:
no_of_players_in_each_team
skill_levels_of_finance_team_players (space separated)
skill_levels_of_marketing_team_players (space separated)
Output Format:
Maximum possible score of Finance team
Constraints:
1 ≤ Number of players ≤ 20
1 ≤ Skill levels ≤ 1000
SAMPLE INPUT
3
8 5 3
8 5 3
SAMPLE OUTPUT
200
Explanation
If similar skills' players were matched, then all three matches would result in a draw (150 points). However, you can assign matches as 8-5, 5-3 and 3-8, resulting in 2 wins and 1 loss (200 points)!
|
{"inputs": ["4\n1 10 7 4\n15 3 8 7"], "outputs": ["250"]}
| 373
| 32
|
coding
|
Solve the programming task below in a Python markdown code block.
Given an `array` of digital numbers, return a new array of length `number` containing the last even numbers from the original array (in the same order). The original array will be not empty and will contain at least "number" even numbers.
For example:
```
([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) => [4, 6, 8]
([-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2) => [-8, 26]
([6, -25, 3, 7, 5, 5, 7, -3, 23], 1) => [6]
```
Also feel free to reuse/extend the following starter code:
```python
def even_numbers(arr,n):
```
|
{"functional": "_inputs = [[[1, 2, 3, 4, 5, 6, 7, 8, 9], 3], [[-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2], [[6, -25, 3, 7, 5, 5, 7, -3, 23], 1]]\n_outputs = [[[4, 6, 8]], [[-8, 26]], [[6]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(even_numbers(*i), o[0])"}
| 217
| 272
|
coding
|
Solve the programming task below in a Python markdown code block.
There are $n$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $1$ to $n$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $i$ ($1 \leq i \leq n$) will decide to go for boiled water at minute $t_i$.
Tank with a boiled water is located to the left of the $1$-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly $p$ minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small.
Nobody likes to stand in a queue. So when the passenger occupying the $i$-th seat wants to go for a boiled water, he will first take a look on all seats from $1$ to $i - 1$. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than $i$ are busy, he will go to the tank.
There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.
Your goal is to find for each passenger, when he will receive the boiled water for his noodles.
-----Input-----
The first line contains integers $n$ and $p$ ($1 \leq n \leq 100\,000$, $1 \leq p \leq 10^9$) — the number of people and the amount of time one person uses the tank.
The second line contains $n$ integers $t_1, t_2, \dots, t_n$ ($0 \leq t_i \leq 10^9$) — the moments when the corresponding passenger will go for the boiled water.
-----Output-----
Print $n$ integers, where $i$-th of them is the time moment the passenger on $i$-th seat will receive his boiled water.
-----Example-----
Input
5 314
0 310 942 628 0
Output
314 628 1256 942 1570
-----Note-----
Consider the example.
At the $0$-th minute there were two passengers willing to go for a water, passenger $1$ and $5$, so the first passenger has gone first, and returned at the $314$-th minute. At this moment the passenger $2$ was already willing to go for the water, so the passenger $2$ has gone next, and so on. In the end, $5$-th passenger was last to receive the boiled water.
|
{"inputs": ["1 1\n1\n", "1 1\n1\n", "1 0\n1\n", "1 0\n0\n", "1 2\n1\n", "5 314\n0 310 942 628 0\n", "5 314\n0 310 942 628 1\n", "5 314\n1 310 942 628 1\n"], "outputs": ["2 \n", "2 ", "1\n", "0\n", "3\n", "314 628 1256 942 1570 \n", "314 628 1256 942 1570\n", "315 629 1257 943 1571\n"]}
| 700
| 211
|
coding
|
Solve the programming task below in a Python markdown code block.
Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.
Original alphabet: abcdefghijklmnopqrstuvwxyz
Alphabet rotated +3: defghijklmnopqrstuvwxyzabc
Example
$s=\textbf{There's-a-star-waiting-in-the-sky}$
$k=3$
The alphabet is rotated by $3$, matching the mapping above. The encrypted string is $\textbf{Wkhuh'v-d-vwdupdq-zdlwlqj-lq-wkh-vnb}$.
Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted.
Function Description
Complete the caesarCipher function in the editor below.
caesarCipher has the following parameter(s):
string s: cleartext
int k: the alphabet rotation factor
Returns
string: the encrypted string
Input Format
The first line contains the integer, $n$, the length of the unencrypted string.
The second line contains the unencrypted string, $\boldsymbol{\mathrm{~S~}}$.
The third line contains $\boldsymbol{\mbox{k}}$, the number of letters to rotate the alphabet by.
Constraints
$1\leq n\leq100$
$0\leq k\leq100$
$\boldsymbol{\mathrm{~S~}}$ is a valid ASCII string without any spaces.
Sample Input
11
middle-Outz
2
Sample Output
okffng-Qwvb
Explanation
Original alphabet: abcdefghijklmnopqrstuvwxyz
Alphabet rotated +2: cdefghijklmnopqrstuvwxyzab
m -> o
i -> k
d -> f
d -> f
l -> n
e -> g
- -
O -> Q
u -> w
t -> v
z -> b
|
{"inputs": ["11\nmiddle-Outz\n2\n"], "outputs": ["okffng-Qwvb\n"]}
| 464
| 26
|
coding
|
Solve the programming task below in a Python markdown code block.
A policeman wants to catch a thief. Both the policeman and the thief can only move on a line on integer coordinates between $0$ and $N$ (inclusive).
Initially, the policeman is at a coordinate $x$ and the thief is at a coordinate $y$. During each second, each of them must move to the left or right (not necessarily both in the same direction) by distance $\textbf{exactly}$ equal to $K$. No one may go to the left of the coordinate $0$ or to the right of $N$. Both the policeman and the thief move simultaneously and they cannot meet while moving, only at the end of each second.
Will the policeman be able to catch the thief if they both move optimally? The thief is caught as soon as the policeman and thief meet at the same position at the same time.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains four space-separated integers $x$, $y$, $K$ and $N$.
-----Output-----
For each test case, print a single line containing the string "Yes" if the thief can be caught or "No" if the thief cannot be caught (without quotes).
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^9$
- $1 \le K \le N$
- $0 \le x, y \le N$
- $x \neq y$
-----Example Input-----
5
0 1 1 1
1 4 1 5
4 2 1 7
3 7 2 10
8 2 3 15
-----Example Output-----
No
No
Yes
Yes
Yes
-----Explanation-----
Example case 1: The policeman is at $0$ and the thief is at $1$. After the $1$-st second, the policeman is at $1$ and the thief is at $0$. After the next second, the policeman is again at $0$ and the thief at $1$. They cannot end up at the same coordinate.
|
{"inputs": ["5\n0 1 1 1\n1 4 1 5\n4 2 1 7\n3 7 2 10\n8 2 3 15"], "outputs": ["No\nNo\nYes\nYes\nYes"]}
| 488
| 62
|
coding
|
Solve the programming task below in a Python markdown code block.
Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..
From a road square, you can move to a horizontally or vertically adjacent road square.
You cannot move out of the maze, move to a wall square, or move diagonally.
Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.
Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.
In this situation, find the maximum possible number of moves Aoki has to make.
-----Constraints-----
- 1 \leq H,W \leq 20
- S_{ij} is . or #.
- S contains at least two occurrences of ..
- Any road square can be reached from any road square in zero or more moves.
-----Input-----
Input is given from Standard Input in the following format:
H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}
-----Output-----
Print the maximum possible number of moves Aoki has to make.
-----Sample Input-----
3 3
...
...
...
-----Sample Output-----
4
If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.
|
{"inputs": ["1 2\n..\n", "3 3\n...\n../\n...", "3 3\n...\n...\n...", "3 3\n...\n...\n...\n", "0 5\n...#.\n.#.#.\n.#...", "0 5\n.#...\n.#.#.\n.#...", "0 5\n.#...\n.#.#.\n.$...", "0 5\n.#..-\n.#.#.\n.$..."], "outputs": ["1\n", "4\n", "4", "4\n", "0\n", "0\n", "0\n", "0\n"]}
| 341
| 137
|
coding
|
Solve the programming task below in a Python markdown code block.
The number ```89``` is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata.
What's the use of saying "Eureka"? Because this sum gives the same number.
In effect: ```89 = 8^1 + 9^2```
The next number in having this property is ```135```.
See this property again: ```135 = 1^1 + 3^2 + 5^3```
We need a function to collect these numbers, that may receive two integers ```a```, ```b``` that defines the range ```[a, b]``` (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.
Let's see some cases:
```python
sum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
sum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
```
If there are no numbers of this kind in the range [a, b] the function should output an empty list.
```python
sum_dig_pow(90, 100) == []
```
Enjoy it!!
Also feel free to reuse/extend the following starter code:
```python
def sum_dig_pow(a, b):
```
|
{"functional": "_inputs = [[1, 100], [10, 89], [10, 100], [90, 100], [90, 150], [50, 150], [10, 150], [89, 135]]\n_outputs = [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 89]], [[89]], [[89]], [[]], [[135]], [[89, 135]], [[89, 135]], [[89, 135]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(sum_dig_pow(*i), o[0])"}
| 339
| 293
|
coding
|
Solve the programming task below in a Python markdown code block.
A (1-indexed) string S of length N is said to be anti-palindrome if, for each 1 ≤ i ≤ N, S_{i} \ne S_{(N + 1 - i)}.
You are given a string S of length N (consisting of lowercase Latin letters only). Rearrange the string to convert it into an anti-palindrome or determine that there is no rearrangement which is an anti-palindrome.
If there are multiple rearrangements of the string which are anti-palindromic, print any of them.
------ Input Format ------
- The first line of input contains a single integer T — the number of test cases. The description of T test cases follows.
- The first line of each test case contains an integer N — the length of the string S.
- The second line of each test case contains the string S.
------ Output Format ------
For each test case, if it is possible to rearrange S to convert it into an anti-palindrome, print YES in the first line and print the rearranged string in the second line. Otherwise, print NO.
You may print each character of YES and NO in uppercase or lowercase (for e.g. yes, yEs, Yes will be considered identical).
If there are multiple rearrangements of the string which are anti-palindromic, print any of them.
------ Constraints ------
$1 ≤ T ≤ 10^{4}$
$1 ≤ N ≤ 10^{5}$
$S$ contains only lowercase Latin letters
- It is guaranteed that the sum of $N$ over all test cases does not exceed $2 \cdot 10^{5}$.
----- Sample Input 1 ------
4
3
abc
8
abccccdd
4
xyyx
6
ppppqr
----- Sample Output 1 ------
NO
YES
abddcccc
YES
xxyy
NO
----- explanation 1 ------
Test case $1$: No matter how the string is rearranged, the condition $S_{i} \ne S_{(N + 1 - i)}$ will not be satisfied for $i = 2$.
Test case $2$: One possible rearrangement of the string which is anti-palindromic is abddcccc. Other answers, such as ccdaccdb, will also be accepted.
Test case $3$: One possible rearrangement of the string which is anti-palindromic is xxyy.
Test case $4$: It can be shown that none of the rearrangements of $A$ is anti-palindromic.
|
{"inputs": ["4\n3\nabc\n8\nabccccdd\n4\nxyyx\n6\nppppqr\n"], "outputs": ["NO\nYES\nabddcccc\nYES\nxxyy\nNO\n"]}
| 562
| 49
|
coding
|
Solve the programming task below in a Python markdown code block.
Let's call the following process a transformation of a sequence of length $n$.
If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $n$ integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence $1, 2, \dots, n$. Find the lexicographically maximum result of its transformation.
A sequence $a_1, a_2, \ldots, a_n$ is lexicographically larger than a sequence $b_1, b_2, \ldots, b_n$, if there is an index $i$ such that $a_j = b_j$ for all $j < i$, and $a_i > b_i$.
-----Input-----
The first and only line of input contains one integer $n$ ($1\le n\le 10^6$).
-----Output-----
Output $n$ integers — the lexicographically maximum result of the transformation.
-----Examples-----
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
-----Note-----
In the first sample the answer may be achieved this way: Append GCD$(1, 2, 3) = 1$, remove $2$. Append GCD$(1, 3) = 1$, remove $1$. Append GCD$(3) = 3$, remove $3$.
We get the sequence $[1, 1, 3]$ as the result.
|
{"inputs": ["3\n", "2\n", "1\n", "4\n", "5\n", "6\n", "7\n", "8\n"], "outputs": ["1 1 3 ", "1 2 ", "1 ", "1 1 2 4 ", "1 1 1 2 4 ", "1 1 1 2 2 6 ", "1 1 1 1 2 2 6 ", "1 1 1 1 2 2 4 8 "]}
| 378
| 119
|
coding
|
Solve the programming task below in a Python markdown code block.
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q.
In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r).
Your task is to read a sequence A and perform the Partition based on the following pseudocode:
Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1
Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r].
Constraints
* 1 ≤ n ≤ 100,000
* 0 ≤ Ai ≤ 100,000
Input
The first line of the input includes an integer n, the number of elements in the sequence A.
In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters.
Output
Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [ ].
Example
Input
12
13 19 9 5 12 8 7 4 21 2 6 11
Output
9 5 8 7 4 2 6 [11] 21 13 19 12
|
{"inputs": ["12\n13 19 9 5 12 8 7 4 13 0 6 3", "12\n13 19 9 5 12 8 7 4 21 0 2 18", "12\n13 19 9 5 12 8 7 4 13 0 6 18", "12\n8 19 9 5 12 8 7 4 21 4 10 18", "12\n13 19 9 5 12 8 7 4 40 0 10 1", "12\n40 19 9 1 12 8 8 6 21 0 10 1", "12\n40 19 6 1 12 8 0 2 21 2 4 22", "12\n13 19 9 5 12 8 7 4 21 2 6 11"], "outputs": ["0 [3] 9 5 12 8 7 4 13 13 6 19\n", "13 9 5 12 8 7 4 0 2 [18] 21 19\n", "13 9 5 12 8 7 4 13 0 6 [18] 19\n", "8 9 5 12 8 7 4 4 10 [18] 21 19\n", "0 [1] 9 5 12 8 7 4 40 13 10 19\n", "1 0 [1] 40 12 8 8 6 21 19 10 9\n", "19 6 1 12 8 0 2 21 2 4 [22] 40\n", "9 5 8 7 4 2 6 [11] 21 13 19 12"]}
| 486
| 523
|
coding
|
Solve the programming task below in a Python markdown code block.
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
Input
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads.
Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
Output
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
Examples
Input
2
0 5
5 0
1
1 2 3
Output
3
Input
3
0 4 5
4 0 9
5 9 0
2
2 3 8
1 2 1
Output
17 12
|
{"inputs": ["2\n0 5\n5 0\n1\n1 2 5\n", "2\n0 5\n5 0\n1\n1 2 3\n", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1\n", "3\n0 983 173\n983 0 810\n173 810 0\n3\n3 2 567\n2 3 767\n1 2 763\n", "3\n0 983 173\n983 0 810\n173 810 0\n3\n2 2 567\n2 3 767\n1 2 763\n", "3\n0 983 173\n983 0 810\n173 810 0\n3\n2 3 567\n2 3 767\n1 2 763\n", "3\n0 983 173\n983 0 810\n173 810 0\n3\n2 2 567\n2 3 767\n1 2 294\n", "3\n0 983 173\n983 0 810\n173 810 0\n3\n2 2 567\n2 3 537\n1 2 294\n"], "outputs": ["5 ", "3\n", "17 12\n", "1480 1480 1480\n", "1966 1880 1703 ", "1480 1480 1480 ", "1966 1880 934 ", "1966 1420 934 "]}
| 589
| 477
|
coding
|
Solve the programming task below in a Python markdown code block.
Alex decided to go on a touristic trip over the country.
For simplicity let's assume that the country has $n$ cities and $m$ bidirectional roads connecting them. Alex lives in city $s$ and initially located in it. To compare different cities Alex assigned each city a score $w_i$ which is as high as interesting city seems to Alex.
Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city $v$ from city $u$, he may choose as the next city in the trip any city connected with $v$ by the road, except for the city $u$.
Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.
-----Input-----
First line of input contains two integers $n$ and $m$, ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) which are numbers of cities and roads in the country.
Second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \le w_i \le 10^9$) which are scores of all cities.
The following $m$ lines contain description of the roads. Each of these $m$ lines contains two integers $u$ and $v$ ($1 \le u, v \le n$) which are cities connected by this road.
It is guaranteed that there is at most one direct road between any two cities, no city is connected to itself by the road and, finally, it is possible to go from any city to any other one using only roads.
The last line contains single integer $s$ ($1 \le s \le n$), which is the number of the initial city.
-----Output-----
Output single integer which is the maximum possible sum of scores of visited cities.
-----Examples-----
Input
5 7
2 2 8 6 9
1 2
1 3
2 4
3 2
4 5
2 5
1 5
2
Output
27
Input
10 12
1 7 1 9 3 3 6 30 1 10
1 2
1 3
3 5
5 7
2 3
5 4
6 9
4 6
3 7
6 8
9 4
9 10
6
Output
61
|
{"inputs": ["1 0\n1000000000\n1\n", "1 0\n1000000000\n1\n", "1 0\n1000000000\n1\n", "1 0\n1000010000\n1\n", "2 1\n999999999 2\n1 2\n2\n", "2 1\n999999999 2\n1 2\n2\n", "2 1\n999999999 2\n1 2\n2\n", "2 1\n999999999 4\n1 2\n2\n"], "outputs": ["1000000000\n", "1000000000\n", "1000000000\n", "1000010000\n", "1000000001\n", "1000000001\n", "1000000001\n", "1000000003\n"]}
| 586
| 282
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.
At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.
Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.
Please complete the following python code precisely:
```python
class Solution:
def memLeak(self, memory1: int, memory2: int) -> List[int]:
```
|
{"functional": "def check(candidate):\n assert candidate(memory1 = 2, memory2 = 2) == [3,1,0]\n assert candidate(memory1 = 8, memory2 = 11) == [6,0,4]\n\n\ncheck(Solution().memLeak)"}
| 204
| 69
|
coding
|
Solve the programming task below in a Python markdown code block.
Taro Aizu's company has a boss who hates being indivisible. When Taro goes out to eat with his boss, he pays by splitting the bill, but when the payment amount is not divisible by the number of participants, his boss always pays for it.
One day, Taro became the secretary of the dinner party. Mr. Taro, who has little money, wondered if he could invite his boss to get a treat. I have to place an order with a restaurant, but I don't know how many people will participate yet, so it seems that I want to place an order so that any number of people can participate. At the same time as Mr. Taro, you who are also planning to attend the dinner party decided to cooperate with Mr. Taro to calculate the amount that is less than the budget amount and is not divisible by any number of people.
Create a program that inputs the type of dish, the price of each dish, and the budget amount, and outputs the total amount (excluding 1 and the total amount) that is not divisible by any number that is less than or equal to the budget amount. You can order multiple dishes of each type, but you do not have to order all types of dishes. However, if there is no such total amount, output NA.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n x
v1
v2
::
vn
On the first line, the type of dish n (1 ≤ n ≤ 30) and the budget amount x (1 ≤ x ≤ 1000000) are given, separated by blanks. The next n lines are given the integer vi (1 ≤ vi ≤ 1000000), which represents the amount of the i-type dish.
The number of datasets does not exceed 100.
Output
For each input dataset, print the total amount or NA closest to the budget amount on one line.
Example
Input
4 15000
305
260
129
500
3 400
10
20
30
3 200909
5
9
12
0 0
Output
14983
NA
200909
|
{"inputs": ["4 15000\n305\n24\n129\n500\n3 349\n9\n20\n30\n3 5016\n5\n9\n12\n0 0", "4 15000\n305\n24\n129\n949\n3 568\n9\n20\n30\n3 5016\n5\n9\n12\n0 0", "4 1512\n305\n17\n129\n129\n3 709\n6\n20\n52\n3 200909\n8\n6\n9\n0 0", "4 1512\n305\n17\n129\n129\n3 709\n6\n20\n52\n3 319036\n8\n6\n9\n0 0", "4 7955\n305\n24\n129\n177\n3 547\n6\n20\n30\n3 200909\n5\n9\n32\n0 0", "4 15000\n305\n24\n129\n500\n3 349\n10\n20\n30\n3 5016\n5\n9\n12\n0 0", "4 4241\n305\n17\n129\n129\n3 547\n6\n20\n30\n3 200909\n5\n9\n22\n0 0", "4 15000\n305\n17\n129\n129\n3 547\n6\n20\n30\n3 35853\n8\n9\n22\n0 0"], "outputs": ["14983\n349\n5011\n", "14983\n563\n5011\n", "1511\nNA\n200909\n", "1511\nNA\n319031\n", "7951\nNA\n200909\n", "14983\nNA\n5011\n", "4241\nNA\n200909\n", "14983\nNA\n35851\n"]}
| 516
| 587
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given a string s of '(' , ')' and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
It is the empty string, contains only lowercase characters, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
Please complete the following python code precisely:
```python
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
```
|
{"functional": "def check(candidate):\n assert candidate(s = \"lee(t(c)o)de)\") == \"lee(t(c)o)de\"\n assert candidate(s = \"a)b(c)d\") == \"ab(c)d\"\n assert candidate(s = \"))((\") == \"\"\n\n\ncheck(Solution().minRemoveToMakeValid)"}
| 159
| 77
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given strings $S$ and $T$, consisting of lowercase English letters. It is guaranteed that $T$ is a permutation of the string abc.
Find string $S'$, the lexicographically smallest permutation of $S$ such that $T$ is not a subsequence of $S'$.
String $a$ is a permutation of string $b$ if the number of occurrences of each distinct character is the same in both strings.
A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.
A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:
$a$ is a prefix of $b$, but $a \ne b$;
in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
-----Input-----
Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a string $S$ ($1 \le |S| \le 100$), consisting of lowercase English letters.
The second line of each test case contains a string $T$ that is a permutation of the string abc. (Hence, $|T| = 3$).
Note that there is no limit on the sum of $|S|$ across all test cases.
-----Output-----
For each test case, output a single string $S'$, the lexicographically smallest permutation of $S$ such that $T$ is not a subsequence of $S'$.
-----Examples-----
Input
7
abacaba
abc
cccba
acb
dbsic
bac
abracadabra
abc
dddddddddddd
cba
bbc
abc
ac
abc
Output
aaaacbb
abccc
bcdis
aaaaacbbdrr
dddddddddddd
bbc
ac
-----Note-----
In the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.
In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.
In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence.
|
{"inputs": ["7\nabacaba\nabc\ncccba\nacb\ndbsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\nbbc\nabc\nac\nabc\n", "7\nabacaba\nabc\ncccba\nacb\ndbsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\nbbc\nabd\nac\nabc\n", "7\nabacaba\nabc\ncccba\nacb\nebsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\nbbc\nabc\nac\nabc\n", "7\nabacaba\nabc\ncccba\nacb\nebsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\ncbc\nabc\nac\nabc\n", "7\nabababa\nabc\ncccba\nacb\ndbsic\nbac\nabracadabra\nabc\ndddddddddddd\nabc\nbbc\nabc\nac\nabc\n", "7\nabacaba\nabc\ncccba\nbca\nebsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\ncbc\ncba\ncb\nacb\n", "7\nabacaba\ncba\ncccba\nbca\nebsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\ncbc\ncba\ncb\nacb\n", "7\nabacaba\nabc\ncccba\nacb\ndbsic\nbac\nabracadabra\nabc\ndddddddddddd\ncba\nbbc\nabd\nbc\nabc\n"], "outputs": ["aaaacbb\nabccc\nbcdis\naaaaacbbdrr\ndddddddddddd\nbbc\nac\n", "aaaacbb\nabccc\nbcdis\naaaaacbbdrr\ndddddddddddd\nbbc\nac\n", "aaaacbb\nabccc\nbceis\naaaaacbbdrr\ndddddddddddd\nbbc\nac\n", "aaaacbb\nabccc\nbceis\naaaaacbbdrr\ndddddddddddd\nbcc\nac\n", "aaaabbb\nabccc\nbcdis\naaaaacbbdrr\ndddddddddddd\nbbc\nac\n", "aaaacbb\nabccc\nbceis\naaaaacbbdrr\ndddddddddddd\nbcc\nbc\n", "aaaabbc\nabccc\nbceis\naaaaacbbdrr\ndddddddddddd\nbcc\nbc\n", "aaaacbb\nabccc\nbcdis\naaaaacbbdrr\ndddddddddddd\nbbc\nbc\n"]}
| 559
| 587
|
coding
|
Solve the programming task below in a Python markdown code block.
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up!
Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $[1,2,3]$ can yield $[3,1,2]$ but it cannot yield $[3,2,1]$ since the $2$ is in the same position.
Given a permutation of $n$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $10^{18}$.
An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows.
The first line of each test case contains integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the length of the given permutation.
The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ ($1 \leq a_{i} \leq n$) — the initial permutation.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.
-----Example-----
Input
2
5
1 2 3 4 5
7
3 2 4 5 1 6 7
Output
0
2
-----Note-----
In the first permutation, it is already sorted so no exchanges are needed.
It can be shown that you need at least $2$ exchanges to sort the second permutation.
$[3, 2, 4, 5, 1, 6, 7]$
Perform special exchange on range ($1, 5$)
$[4, 1, 2, 3, 5, 6, 7]$
Perform special exchange on range ($1, 4$)
$[1, 2, 3, 4, 5, 6, 7]$
|
{"inputs": ["1\n2\n1 2\n", "1\n2\n1 2\n", "1\n4\n2 1 3 4\n", "1\n4\n2 1 3 4\n", "1\n3\n2 1 3 4\n", "1\n4\n2 1 2 4\n", "1\n3\n2 0 3 4\n", "1\n5\n1 3 4 2 5\n"], "outputs": ["0\n", "0\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
| 647
| 144
|
coding
|
Solve the programming task below in a Python markdown code block.
Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.
A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.
When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.
At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.
In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 10^5
- 1 \leq K \leq 10^9
- 1 \leq Q \leq 10^5
- 1 \leq A_i \leq N\ (1 \leq i \leq Q)
-----Input-----
Input is given from Standard Input in the following format:
N K Q
A_1
A_2
.
.
.
A_Q
-----Output-----
Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.
-----Sample Input-----
6 3 4
3
1
3
2
-----Sample Output-----
No
No
Yes
No
No
No
In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).
- Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).
- Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).
- Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).
- Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).
Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.
|
{"inputs": ["6 1 4\n3\n1\n3\n2", "6 3 4\n3\n1\n3\n4", "6 5 4\n3\n0\n3\n2", "8 1 4\n3\n1\n0\n2", "6 3 4\n6\n1\n3\n1", "8 1 1\n4\n1\n0\n2", "8 5 3\n3\n0\n4\n2", "9 1 0\n6\n1\n3\n4"], "outputs": ["No\nNo\nNo\nNo\nNo\nNo\n", "No\nNo\nYes\nNo\nNo\nNo\n", "Yes\nYes\nYes\nYes\nYes\nYes\n", "No\nNo\nNo\nNo\nNo\nNo\nNo\nNo\n", "Yes\nNo\nNo\nNo\nNo\nNo\n", "No\nNo\nNo\nYes\nNo\nNo\nNo\nNo\n", "Yes\nYes\nYes\nYes\nYes\nYes\nYes\nYes\n", "Yes\nYes\nYes\nYes\nYes\nYes\nYes\nYes\nYes\n"]}
| 565
| 256
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Please complete the following python code precisely:
```python
class Solution:
def getPermutation(self, n: int, k: int) -> str:
```
|
{"functional": "def check(candidate):\n assert candidate(n = 3, k = 3) == \"213\"\n assert candidate(n = 4, k = 9) == \"2314\"\n assert candidate(n = 3, k = 1) == \"123\"\n\n\ncheck(Solution().getPermutation)"}
| 140
| 81
|
coding
|
Solve the programming task below in a Python markdown code block.
We'll define S(n) for positive integer n as follows: the number of the n's digits in the decimal base. For example, S(893) = 3, S(114514) = 6.
You want to make a consecutive integer sequence starting from number m (m, m + 1, ...). But you need to pay S(n)·k to add the number n to the sequence.
You can spend a cost up to w, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.
-----Input-----
The first line contains three integers w (1 ≤ w ≤ 10^16), m (1 ≤ m ≤ 10^16), k (1 ≤ k ≤ 10^9).
Please, do not write the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
The first line should contain a single integer — the answer to the problem.
-----Examples-----
Input
9 1 1
Output
9
Input
77 7 7
Output
7
Input
114 5 14
Output
6
Input
1 1 2
Output
0
|
{"inputs": ["9 1 1\n", "1 1 2\n", "3 1 4\n", "1 1 1\n", "3 1 4\n", "1 1 1\n", "3 1 5\n", "2 1 2\n"], "outputs": ["9\n", "0\n", "0\n", "1\n", "0\n", "1\n", "0\n", "1\n"]}
| 295
| 102
|
coding
|
Solve the programming task below in a Python markdown code block.
itertools.combinations_with_replacement(iterable, r)
This tool returns $\textbf{r}$ length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Sample Code
>>> from itertools import combinations_with_replacement
>>>
>>> print list(combinations_with_replacement('12345',2))
[('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '2'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '3'), ('3', '4'), ('3', '5'), ('4', '4'), ('4', '5'), ('5', '5')]
>>>
>>> A = [1,1,3,3,3]
>>> print list(combinations(A,2))
[(1, 1), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (3, 3), (3, 3), (3, 3)]
Task
You are given a string $\mbox{S}$.
Your task is to print all possible size $\boldsymbol{\mbox{k}}$ replacement combinations of the string in lexicographic sorted order.
Input Format
A single line containing the string $\mbox{S}$ and integer value $\boldsymbol{\mbox{k}}$ separated by a space.
Constraints
$0<k\leq len(S)$
The string contains only UPPERCASE characters.
Output Format
Print the combinations with their replacements of string $\mbox{S}$ on separate lines.
Sample Input
HACK 2
Sample Output
AA
AC
AH
AK
CC
CH
CK
HH
HK
KK
|
{"inputs": ["HACK 2\n"], "outputs": ["AA\nAC\nAH\nAK\nCC\nCH\nCK\nHH\nHK\nKK\n"]}
| 440
| 35
|
coding
|
Solve the programming task below in a Python markdown code block.
Arthur defines a function, $f(k)$, to be the number of $(p,q)$ pairs such that:
$1<p\leq q\leq k$
${p}$ and $q}$ are coprime.
$p\cdot q=k$
Given an integer, $n$, help Arthur find and print the result of:
$\sum_{k=1}^{n}f(k)$
Input Format
The first line contains a single integer denoting $n$.
Constraints
$1\leq n\leq10^9$
Subtasks
$1\leq n\leq150$ for $30\%$ of the maximum score.
$1\leq n\leq10^{6}$ for ${60%}$ of the maximum score.
Output Format
Print the result of $\textstyle\sum_{k=1}^{n}f(k)$ on a new line.
Sample Input
12
Sample Output
3
Explanation
The value of $f(k)$ for $1\leq k\leq12$ is:
For $k=6$, there is only $\mbox{I}$ valid pair, $(2,3)$, so $f(6)=1$.
For $k=10$, there is only $\mbox{I}$ valid pair, $(2,5)$, so $f(10)=1$
For $k=12$, there is only $\mbox{I}$ valid pair, $(3,4)$, so $f(12)=1$
For all other $1\leq k\leq12$, the function returns $\mbox{0}$.
Thus, our final sum is the result of $1+1+1=3$.
|
{"inputs": ["12\n"], "outputs": ["3\n"]}
| 390
| 15
|
coding
|
Solve the programming task below in a Python markdown code block.
Find the difference of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$, $A - B$.
Constraints
* $1 \leq n, m \leq 200,000$
* $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$
* $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ... \; a_{n-1}$
$m$
$b_0 \; b_1 \; ... \; b_{m-1}$
Elements in $A$ and $B$ are given in ascending order. There are no duplicate elements in each set.
Output
Print elements in the difference in ascending order. Print an element in a line.
Example
Input
5
1 2 3 5 8
2
2 5
Output
1
3
8
|
{"inputs": ["5\n1 2 3 5 8\n2\n4 5", "5\n1 2 3 5 8\n0\n4 5", "5\n0 2 3 5 8\n0\n0 5", "5\n0 2 3 5 8\n2\n4 5", "5\n0 2 3 5 7\n2\n4 9", "5\n0 2 3 5 6\n3\n4 9", "5\n1 2 4 5 8\n0\n0 2", "5\n1 2 4 6 8\n0\n2 5"], "outputs": ["1\n2\n3\n8\n", "1\n2\n3\n5\n8\n", "0\n2\n3\n5\n8\n", "0\n2\n3\n8\n", "0\n2\n3\n5\n7\n", "0\n2\n3\n5\n6\n", "1\n2\n4\n5\n8\n", "1\n2\n4\n6\n8\n"]}
| 280
| 250
|
coding
|
Solve the programming task below in a Python markdown code block.
Chef is given a sequence of prime numbers $A_1, A_2, \ldots, A_N$. This sequence has exactly $2^N$ subsequences. A subsequence of $A$ is good if it does not contain any two identical numbers; in particular, the empty sequence is good.
Chef has to find the number of good subsequences which contain at most $K$ numbers. Since he does not know much about subsequences, help him find the answer. This number could be very large, so compute it modulo $1,000,000,007$.
-----Input-----
- The first line of the input contains two space-separated integers $N$ and $K$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
-----Output-----
Print a single line containing one integer ― the number of good subsequences with size at most $K$, modulo $1,000,000,007$.
-----Constraints-----
- $1 \le K \le N \le 10^5$
- $2 \le A_i \le 8,000$ for each valid $i$
-----Subtasks-----
Subtask #1 (40 points): $A_1, A_2, \ldots, A_N$ are pairwise distinct
Subtask #2 (60 points): original constraints
-----Example Input-----
5 3
2 2 3 3 5
-----Example Output-----
18
-----Explanation-----
There is $1$ good subsequence with length $0$, $5$ good subsequences with length $1$, $8$ good subsequences with length $2$ and $4$ good subsequences with length $3$.
|
{"inputs": ["5 3\n2 2 3 3 5"], "outputs": ["18"]}
| 393
| 25
|
coding
|
Solve the programming task below in a Python markdown code block.
n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
-----Input-----
The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 10^12) — the number of people and the number of wins.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all a_{i} are distinct.
-----Output-----
Output a single integer — power of the winner.
-----Examples-----
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
-----Note-----
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.
|
{"inputs": ["2 2\n1 2\n", "2 2\n1 2\n", "3 2\n1 3 2\n", "3 3\n1 2 3\n", "3 3\n1 2 3\n", "3 2\n1 3 2\n", "3 2\n2 3 2\n", "3 2\n2 3 0\n"], "outputs": ["2 ", "2", "3 ", "3 ", "3", "3", "3\n", "3\n"]}
| 374
| 124
|
coding
|
Solve the programming task below in a Python markdown code block.
A sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day d_{i} he will deposit t_{i} rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following m days.
Determine the number of days starting from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.
-----Input-----
The first line contains three integers n, p and m (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 10^9, 1 ≤ m ≤ 10^9, n ≤ m) — the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check.
The i-th of the following n lines contains two integers d_{i} and t_{i} (1 ≤ d_{i} ≤ m, 1 ≤ t_{i} ≤ 10^9) — the index of the day when Arkady will make the i-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i. e. d_{i} > d_{i} - 1 for all i from 2 to n.
-----Output-----
Print the number of days from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment.
-----Examples-----
Input
3 6 7
2 13
4 20
7 9
Output
3
Input
5 4 100
10 70
15 76
21 12
30 100
67 85
Output
26
-----Note-----
In the first example the balance will change as following (remember, initially the balance is zero): in the first day 6 rubles will be charged, the balance in the evening will be equal to - 6; in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1; in the third day 6 rubles will be charged, the balance in the evening will be equal to - 5; in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9; in the fifth day 6 rubles will be charged, the balance in the evening will be equal to 3; in the sixth day 6 rubles will be charged, the balance in the evening will be equal to - 3; in the seventh day Arkady will deposit 9 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 0.
Thus, in the end of the first, third and sixth days the balance will be negative in the end of the day.
|
{"inputs": ["1 1 1\n1 1\n", "1 2 1\n1 1\n", "1 2 1\n1 3\n", "1 1 1\n1 1\n", "1 2 1\n1 1\n", "1 2 1\n1 3\n", "1 2 1\n1 0\n", "1 4 1\n1 3\n"], "outputs": ["0\n", "1\n", "0\n", " 0", " 1", " 0", "1\n", "1\n"]}
| 723
| 137
|
coding
|
Solve the programming task below in a Python markdown code block.
Takahashi is playing with N cards.
The i-th card has an integer X_i on it.
Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:
* The integers on the two cards are the same.
* The sum of the integers on the two cards is a multiple of M.
Find the maximum number of pairs that can be created.
Note that a card cannot be used in more than one pair.
Constraints
* 2≦N≦10^5
* 1≦M≦10^5
* 1≦X_i≦10^5
Input
The input is given from Standard Input in the following format:
N M
X_1 X_2 ... X_N
Output
Print the maximum number of pairs that can be created.
Examples
Input
7 5
3 1 4 1 5 9 2
Output
3
Input
15 10
1 5 6 10 11 11 11 20 21 25 25 26 99 99 99
Output
6
|
{"inputs": ["7 5\n3 1 4 1 5 9 3", "7 5\n3 1 4 1 5 8 3", "7 8\n4 2 5 1 5 9 3", "7 5\n3 1 4 1 5 4 3", "7 1\n3 1 4 1 5 4 3", "7 1\n4 1 4 1 5 4 3", "7 1\n6 1 4 1 5 4 3", "7 1\n6 0 4 1 5 4 3"], "outputs": ["3\n", "2\n", "1\n", "3\n", "3\n", "3\n", "3\n", "3\n"]}
| 261
| 190
|
coding
|
Solve the programming task below in a Python markdown code block.
# Task
Sorting is one of the most basic computational devices used in Computer Science.
Given a sequence (length ≤ 1000) of 3 different key values (7, 8, 9), your task is to find the minimum number of exchange operations necessary to make the sequence sorted.
One operation is the switching of 2 key values in the sequence.
# Example
For `sequence = [7, 7, 8, 8, 9, 9]`, the result should be `0`.
It's already a sorted sequence.
For `sequence = [9, 7, 8, 8, 9, 7]`, the result should be `1`.
We can switching `sequence[0]` and `sequence[5]`.
For `sequence = [8, 8, 7, 9, 9, 9, 8, 9, 7]`, the result should be `4`.
We can:
```
[8, 8, 7, 9, 9, 9, 8, 9, 7]
switching sequence[0] and sequence[3]
--> [9, 8, 7, 8, 9, 9, 8, 9, 7]
switching sequence[0] and sequence[8]
--> [7, 8, 7, 8, 9, 9, 8, 9, 9]
switching sequence[1] and sequence[2]
--> [7, 7, 8, 8, 9, 9, 8, 9, 9]
switching sequence[5] and sequence[7]
--> [7, 7, 8, 8, 8, 9, 9, 9, 9]
```
So `4` is the minimum number of operations for the sequence to become sorted.
# Input/Output
- `[input]` integer array `sequence`
The Sequence.
- `[output]` an integer
the minimum number of operations.
Also feel free to reuse/extend the following starter code:
```python
def exchange_sort(sequence):
```
|
{"functional": "_inputs = [[[7, 7, 8, 8, 9, 9]], [[9, 7, 8, 8, 9, 7]], [[8, 8, 7, 9, 9, 9, 8, 9, 7]], [[9, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7]], [[9, 9, 9, 7, 7, 8, 9, 7, 8, 9, 7, 9]], [[9, 9, 7, 7, 8, 8]], [[9, 7, 9]], [[8, 7, 8]], [[7, 8, 7, 8]], [[8, 8, 7, 8]], [[8, 8, 7, 7, 8]]]\n_outputs = [[0], [1], [4], [6], [4], [4], [1], [1], [1], [1], [2]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(exchange_sort(*i), o[0])"}
| 480
| 401
|
coding
|
Solve the programming task below in a Python markdown code block.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
{"inputs": ["habege\necjecg\n0\n", "habege\ngcejce\n0\n", "habege\ngceice\n0\n", "habfge\ngceice\n0\n", "habfge\ngdeice\n0\n", "habfge\nedeicg\n0\n", "a\nb\n3\na b 2\na b 3\nb a 5\n", "uayd\nuxxd\n3\na x 8\nx y 13\nd c 2\n"], "outputs": ["-1\n", "-1\n", "-1\n", "-1\n", "-1\n", "-1\n", "2\nb\n", "21\nuxyd\n"]}
| 426
| 167
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an integer array nums, return the largest integer that only occurs once. If no integer occurs once, return -1.
Please complete the following python code precisely:
```python
class Solution:
def largestUniqueNumber(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate([5,7,3,9,4,9,8,3,1]) == 8\n assert candidate([9,9,8,8]) == -1\n\n\ncheck(Solution().largestUniqueNumber)"}
| 74
| 63
|
coding
|
Solve the programming task below in a Python markdown code block.
Integral numbers can be even or odd.
Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :]
Even numbers are just not odd.
# Task
Given a finite list of integral ( not necessarily non-negative ) numbers, determine the number that is _odder than the rest_.
If there is no single such number, no number is odder than the rest; return `Nothing`, `null` or a similar empty value.
# Examples
```python
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => None
```
# Hint
Do you _really_ want one? Point or tap here.
Also feel free to reuse/extend the following starter code:
```python
def oddest(a):
```
|
{"functional": "_inputs = [[[1, 2]], [[1, 3]], [[1, 5]], [[]], [[0]], [[0, 1]], [[1, 3, 5, 7]], [[2, 4]], [[-1]], [[-1, -1]], [[-1, 0, 1]], [[-3, 3]], [[-5, 3]]]\n_outputs = [[1], [3], [None], [None], [0], [1], [7], [None], [-1], [None], [-1], [3], [None]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(oddest(*i), o[0])"}
| 240
| 269
|
coding
|
Solve the programming task below in a Python markdown code block.
Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $s$ of length $n$.
Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $s$.
She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $s$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.
A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. The next $2 \cdot t$ lines contain the description of test cases. The description of each test case consists of two lines.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the length of the string.
The second line of each test case contains the string $s$ consisting of $n$ lowercase English letters.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $-1$, if it is impossible.
-----Examples-----
Input
5
8
abcaacab
6
xyzxyz
4
abba
8
rprarlap
10
khyyhhyhky
Output
2
-1
0
3
2
-----Note-----
In the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.
In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.
In the third test case, you don't have to erase any symbols because the string is already a palindrome.
|
{"inputs": ["5\n8\nabcaacab\n6\nxyzxyz\n4\nabba\n8\nrprarlap\n10\nkhyyhhyhky\n", "5\n8\nabcaacab\n6\nxyzxyz\n4\nabba\n8\nrpqarlap\n10\nkhyyhhyhky\n", "5\n8\nabcaacab\n6\nxyzxyy\n4\nabba\n8\nrpqarlap\n10\nkhyyhhyhky\n", "5\n8\nabcaacab\n6\nxyzxyz\n4\nabab\n8\nrpqarlap\n10\nkhyyhhyhky\n", "5\n8\nabcaacab\n6\nxyzxyy\n4\nabba\n8\nrpqarlap\n10\nkyyyhhhhky\n", "5\n8\nabcaacab\n6\nxyzxyz\n4\nabab\n8\nrprarlap\n10\nkhyyhhyhky\n", "5\n8\nabcaacaa\n6\nxyzxyy\n4\nabba\n8\nrpqarlap\n10\nkyyyhhhhky\n", "5\n8\nabbaacab\n6\nxyzxyz\n4\nabba\n8\nrpqarlap\n10\nykhyhhyyhk\n"], "outputs": ["2\n-1\n0\n3\n2\n", "2\n-1\n0\n-1\n2\n", "2\n3\n0\n-1\n2\n", "2\n-1\n1\n-1\n2\n", "2\n3\n0\n-1\n4\n", "2\n-1\n1\n3\n2\n", "-1\n3\n0\n-1\n4\n", "-1\n-1\n0\n-1\n2\n"]}
| 622
| 415
|
coding
|
Solve the programming task below in a Python markdown code block.
Given an array of integers, find the sum of its elements.
For example, if the array $ar=[1,2,3]$, $1+2+3=6$, so return $6$.
Function Description
Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.
simpleArraySum has the following parameter(s):
ar: an array of integers
Input Format
The first line contains an integer, $n$, denoting the size of the array.
The second line contains $n$ space-separated integers representing the array's elements.
Constraints
$0<n,ar[i]\leq1000$
Output Format
Print the sum of the array's elements as a single integer.
Sample Input
6
1 2 3 4 10 11
Sample Output
31
Explanation
We print the sum of the array's elements: $1+2+3+4+10+11=31$.
|
{"inputs": ["6\n1 2 3 4 10 11\n"], "outputs": ["31\n"]}
| 231
| 29
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Please complete the following python code precisely:
```python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [-2,1,-3,4,-1,2,1,-5,4]) == 6\n assert candidate(nums = [1]) == 1\n assert candidate(nums = [5,4,-1,7,8]) == 23\n\n\ncheck(Solution().maxSubArray)"}
| 69
| 81
|
coding
|
Solve the programming task below in a Python markdown code block.
The chef was busy in solving algebra, he found some interesting results, that there are many numbers which can be formed by the sum of the factorial of the digits, he wrote all those interesting numbers in the diary(in increasing order) and went to sleep. Cheffina came and stole his diary, in morning chef found that his diary is missing. Now the chef wants your help to find those numbers, Chef asks you whether N is that interesting number or not. If N is an interesting number then print 1. Else print 0.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, $N$.
-----Output:-----
For each test case, output in a single line answer 1 or 0.
-----Constraints-----
- $1 \leq T \leq 10^6$
- $0 \leq N \leq 10^9$
-----Sample Input:-----
2
2
10
-----Sample Output:-----
1
0
-----EXPLANATION:-----
For 1) Factorial of 2 is 2, hence it is an interesting number.
For 2) conversion for 10 is 1! + 0! = 2, which is not equal to 10, hence not an interesting number.
|
{"inputs": ["2\n2\n10"], "outputs": ["1\n0"]}
| 302
| 19
|
coding
|
Solve the programming task below in a Python markdown code block.
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
~~~if-not:racket
```
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
```
~~~
```if:javascript,python,ruby,php,elixir,dart
You can assume that all values are integers. Do not mutate the input array/list.
```
```if:c
### Notes:
- All values are greater than `INT_MIN`
- The input should be modified, not returned.
```
~~~if:racket
```racket
(invert '(1 2 3 4 5)) ; '(-1 -2 -3 -4 -5)
(invert '(1 -2 3 -4 5)) ; '(-1 2 -3 4 -5)
(invert '()) ; '()
```
~~~
Also feel free to reuse/extend the following starter code:
```python
def invert(lst):
```
|
{"functional": "_inputs = [[[1, 2, 3, 4, 5]], [[1, -2, 3, -4, 5]], [[]], [[0]]]\n_outputs = [[[-1, -2, -3, -4, -5]], [[-1, 2, -3, 4, -5]], [[]], [[0]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(invert(*i), o[0])"}
| 262
| 220
|
coding
|
Solve the programming task below in a Python markdown code block.
Given are N positive integers A_1,...,A_N.
Consider positive integers B_1, ..., B_N that satisfy the following condition.
Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds.
Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N.
Since the answer can be enormous, print the sum modulo (10^9 +7).
-----Constraints-----
- 1 \leq N \leq 10^4
- 1 \leq A_i \leq 10^6
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 ... A_N
-----Output-----
Print the minimum possible value of B_1 + ... + B_N for B_1,...,B_N that satisfy the condition, modulo (10^9 +7).
-----Sample Input-----
3
2 3 4
-----Sample Output-----
13
Let B_1=6, B_2=4, and B_3=3, and the condition will be satisfied.
|
{"inputs": ["1\n1\n", "1\n12\n", "3\n2 3 2", "3\n2 6 2", "3\n1 6 2", "3\n3 3 4", "3\n2 5 2", "3\n3 6 2"], "outputs": ["1\n", "1\n", "8\n", "7\n", "10\n", "11\n", "12\n", "6\n"]}
| 270
| 108
|
coding
|
Solve the programming task below in a Python markdown code block.
Some numbers have funny properties. For example:
> 89 --> 8¹ + 9² = 89 * 1
> 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
> 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
- we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n.
In other words:
> Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
**Note**: n and p will always be given as strictly positive integers.
```python
dig_pow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
dig_pow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
dig_pow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
dig_pow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
```
Also feel free to reuse/extend the following starter code:
```python
def dig_pow(n, p):
```
|
{"functional": "_inputs = [[89, 1], [92, 1], [46288, 3], [114, 3], [46288, 5], [135, 1], [175, 1], [518, 1], [598, 1], [1306, 1], [2427, 1], [2646798, 1], [3456789, 1], [3456789, 5], [198, 1], [249, 1], [1377, 1], [1676, 1], [695, 2], [1878, 2], [7388, 2], [47016, 2], [542186, 2], [261, 3], [1385, 3], [2697, 3], [6376, 3], [6714, 3], [63760, 3], [63761, 3], [132921, 3], [10383, 6]]\n_outputs = [[1], [-1], [51], [9], [-1], [1], [1], [1], [1], [1], [1], [1], [-1], [-1], [3], [3], [2], [1], [2], [19], [5], [1], [1], [5], [35], [66], [10], [1], [1], [1], [4], [12933]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(dig_pow(*i), o[0])"}
| 470
| 548
|
coding
|
Solve the programming task below in a Python markdown code block.
Find the intersection of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$.
Constraints
* $1 \leq n, m \leq 200,000$
* $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$
* $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ... \; a_{n-1}$
$m$
$b_0 \; b_1 \; ... \; b_{m-1}$
Elements of $A$ and $B$ are given in ascending order respectively. There are no duplicate elements in each set.
Output
Print elements in the intersection in ascending order. Print an element in a line.
Example
Input
4
1 2 5 8
5
2 3 5 9 11
Output
2
5
|
{"inputs": ["4\n1 3 5 8\n5\n1 3 5 9 7", "4\n1 2 5 8\n5\n2 3 5 9 7", "4\n1 2 5 8\n7\n0 3 5 9 9", "4\n1 2 0 8\n9\n1 3 5 9 6", "4\n1 2 5 8\n5\n4 3 5 9 11", "4\n1 2 5 8\n9\n2 3 5 9 11", "4\n1 2 9 8\n5\n4 3 5 9 11", "4\n1 2 5 8\n9\n1 3 5 9 11"], "outputs": ["1\n3\n5\n", "2\n5\n", "5\n", "1\n", "5\n", "2\n5\n", "9\n", "1\n5\n"]}
| 278
| 236
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].
A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.
Please complete the following python code precisely:
```python
class Solution:
def maxSubarraySumCircular(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [1,-2,3,-2]) == 3\n assert candidate(nums = [5,-3,5]) == 10\n assert candidate(nums = [3,-2,2,-3]) == 3\n\n\ncheck(Solution().maxSubarraySumCircular)"}
| 195
| 75
|
coding
|
Solve the programming task below in a Python markdown code block.
Nick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi at extra cost ci». The qualification qj of each employee is known, and for each application the following is true: qai > qbi.
Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.
Input
The first input line contains integer n (1 ≤ n ≤ 1000) — amount of employees in the company. The following line contains n space-separated numbers qj (0 ≤ qj ≤ 106)— the employees' qualifications. The following line contains number m (0 ≤ m ≤ 10000) — amount of received applications. The following m lines contain the applications themselves, each of them in the form of three space-separated numbers: ai, bi and ci (1 ≤ ai, bi ≤ n, 0 ≤ ci ≤ 106). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai > qbi.
Output
Output the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.
Examples
Input
4
7 2 3 1
4
1 2 5
2 4 1
3 4 1
1 3 5
Output
11
Input
3
1 2 3
2
3 1 2
3 1 3
Output
-1
Note
In the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1.
|
{"inputs": ["1\n2\n0\n", "1\n3\n0\n", "1\n6\n0\n", "1\n10\n0\n", "1\n13\n0\n", "2\n10 5\n0\n", "2\n11 5\n0\n", "2\n14 5\n0\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "-1\n", "-1\n", "-1\n"]}
| 463
| 113
|
coding
|
Solve the programming task below in a Python markdown code block.
You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.
You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display.
The second line contains n digits — the initial state of the display.
-----Output-----
Print a single line containing n digits — the desired state of the display containing the smallest possible number.
-----Examples-----
Input
3
579
Output
024
Input
4
2014
Output
0142
|
{"inputs": ["1\n1\n", "1\n0\n", "1\n0\n", "1\n1\n", "1\n2\n", "1\n3\n", "1\n4\n", "1\n5\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0", "0", "0", "0"]}
| 298
| 82
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
|
{"inputs": ["1 1\na\nb\n", "4 5\nabca\nbaaab\n", "4 5\nabca\nbabab\n", "4 5\nabca\naabab\n", "4 5\nabba\nbabab\n", "6 6\nooojjj\nooookj\n", "7 7\nuiibwws\nqhtkxcn\n", "6 9\nvvvkvv\nvgkkvvvgg\n"], "outputs": ["0\n", "4\n", "5\n", "5\n", "5\n", "7\n", "0\n", "6\n"]}
| 538
| 143
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given N integers. The i-th integer is a_i. Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:
* Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.
Constraints
* 3 \leq N \leq 300
* 1 \leq a_i \leq 300(1\leq i\leq N)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1
:
a_N
Output
Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.
Examples
Input
4
1
1
1
2
Output
18
Input
6
1
3
2
3
5
2
Output
150
Input
20
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9
3
2
3
8
4
Output
563038556
|
{"inputs": ["4\n1\n1\n0\n2", "4\n1\n1\n0\n3", "4\n2\n1\n1\n2", "4\n2\n1\n2\n2", "4\n1\n1\n1\n2", "6\n1\n3\n0\n3\n5\n2", "6\n1\n3\n0\n3\n5\n0", "6\n1\n3\n0\n4\n1\n0"], "outputs": ["998244347\n", "0\n", "6\n", "18\n", "18", "138\n", "78\n", "162\n"]}
| 312
| 152
|
coding
|
Solve the programming task below in a Python markdown code block.
problem
Given the sequence $ A $ of length $ N $. Find the maximum value of $ \ sum B_i $, where $ B $ is one of the longest increasing subsequences of the sequence $ A $.
The longest increasing subsequence of the sequence $ A $ is the longest subsequence that satisfies $ A_i <A_j $ with all $ i <j $.
output
Output the maximum value of $ \ sum B_i $, where $ B $ is one of the longest increasing subsequences of the sequence $ A $. Also, output a line break at the end.
Example
Input
4
6 4 7 8
Output
21
|
{"inputs": ["4\n7 4 7 8", "4\n7 4 1 8", "4\n7 4 2 9", "4\n7 4 2 6", "4\n6 4 3 8", "4\n7 5 7 8", "4\n6 4 3 3", "4\n6 1 3 3"], "outputs": ["19\n", "15\n", "16\n", "10\n", "14\n", "20\n", "6\n", "4\n"]}
| 150
| 132
|
coding
|
Solve the programming task below in a Python markdown code block.
# Kata Task
You are given a list of cogs in a gear train
Each element represents the number of teeth of that cog
e.g. `[100, 50, 25]` means
* 1st cog has 100 teeth
* 2nd cog has 50 teeth
* 3rd cog has 25 teeth
If the ``nth`` cog rotates clockwise at 1 RPM what is the RPM of the cogs at each end of the gear train?
**Notes**
* no two cogs share the same shaft
* return an array whose two elements are RPM of the first and last cogs respectively
* use negative numbers for anti-clockwise rotation
* for convenience `n` is zero-based
* For C and NASM coders, the returned array will be `free`'d.
---
Series:
* Cogs
* Cogs 2
Also feel free to reuse/extend the following starter code:
```python
def cog_RPM(cogs, n):
```
|
{"functional": "_inputs = [[[100], 0], [[100, 100, 100, 100], 0], [[100, 100, 100, 100], 1], [[100, 100, 100, 100], 2], [[100, 100, 100, 100], 3]]\n_outputs = [[[1, 1]], [[1, -1]], [[-1, 1]], [[1, -1]], [[-1, 1]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(cog_RPM(*i), o[0])"}
| 232
| 282
|
coding
|
Solve the programming task below in a Python markdown code block.
Related to MrZizoScream's Product Array kata. You might want to solve that one first :)
```if:javascript
**Note:** Node 10 has now been enabled, and you can now use its BigInt capabilities if you wish, though your resulting array must still contain strings (e.g. "99999999999", not 9999999999n)
Pre-node 10: You will need to use the BigNumber.js library! Please use `.toFixed(0)` or `.toPrecision()` to round instead of `.toString(10)`, as the latter is _very_ slow
```
This is an adaptation of a problem I came across on LeetCode.
Given an array of numbers, your task is to return a new array where each index (`new_array[i]`) is equal to the product of the original array, except for the number at that index (`array[i]`).
**Two things to keep in mind:**
* Zeroes will be making their way into some of the arrays you are given
* O(n^2) solutions will not pass.
Examples:
**Note**: All inputs will be valid arrays of nonzero length.
Have fun! Please upvote if you enjoyed :)
Also feel free to reuse/extend the following starter code:
```python
def product_sans_n(nums):
```
|
{"functional": "_inputs = [[[1, 1, 1]], [[0, -99, 0]], [[9, 0, -2]], [[1, 2, 3, 4]], [[2, 3, 4, 5]], [[-8, 1, 5, 13, -1]], [[3, 14, 9, 11, 11]], [[4, 7, 3, 6, 2, 11, 14, 4, 7, 5]]]\n_outputs = [[[1, 1, 1]], [[0, 0, 0]], [[0, -18, 0]], [[24, 12, 8, 6]], [[60, 40, 30, 24]], [[-65, 520, 104, 40, -520]], [[15246, 3267, 5082, 4158, 4158]], [[5433120, 3104640, 7244160, 3622080, 10866240, 1975680, 1552320, 5433120, 3104640, 4346496]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(product_sans_n(*i), o[0])"}
| 298
| 473
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a function $f(X)=X^2$. You are also given $\mbox{K}$ lists. The $i^{\mbox{th}}$ list consists of $N_i$ elements.
You have to pick one element from each list so that the value from the equation below is maximized:
$S=(f(X_1)~+f(X_2)+~....~+f(X_k))$%$\mbox{M}$
$X_i$ denotes the element picked from the $i^{\mbox{th}}$ list . Find the maximized value $S_{max}$ obtained.
$\gamma_{0}$ denotes the modulo operator.
Note that you need to take exactly one element from each list, not necessarily the largest element. You add the squares of the chosen elements and perform the modulo operation. The maximum value that you can obtain, will be the answer to the problem.
Input Format
The first line contains $2$ space separated integers $\mbox{K}$ and $\mbox{M}$.
The next $\mbox{K}$ lines each contains an integer $N_i$, denoting the number of elements in the $i^{\mbox{th}}$ list, followed by $N_i$ space separated integers denoting the elements in the list.
Constraints
$1\leq K\leq7$
$1\leq M\leq1000$
$1\leq N_i\leq7$
$1\le\textit{Magnitude of elements in list}\le10^9$
Output Format
Output a single integer denoting the value $S_{max}$.
Sample Input
3 1000
2 5 4
3 7 8 9
5 5 7 8 9 10
Sample Output
206
Explanation
Picking $5$ from the $\mbox{I}$^{st} list, $\mbox{9}$ from the $2$^{nd} list and $10$ from the $3$^{rd} list gives the maximum $\mbox{S}$ value equal to $(5^2+9^2+10^2)$%$\textbf{1000}$ = $\textbf{206}$.
|
{"inputs": ["3 1000\n2 5 4\n3 7 8 9 \n5 5 7 8 9 10 \n"], "outputs": ["206\n"]}
| 512
| 50
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Please complete the following python code precisely:
```python
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
```
|
{"functional": "def check(candidate):\n assert candidate(candidates = [2,3,6,7], target = 7) == [[2,2,3],[7]]\n\n\ncheck(Solution().combinationSum)"}
| 155
| 51
|
coding
|
Solve the programming task below in a Python markdown code block.
Write a function
`titleToNumber(title) or title_to_number(title) or titleToNb title ...`
(depending on the language)
that given a column title as it appears in an Excel sheet, returns its corresponding column number. All column titles will be uppercase.
Examples:
```
titleTonumber('A') === 1
titleTonumber('Z') === 26
titleTonumber('AA') === 27
```
Also feel free to reuse/extend the following starter code:
```python
def title_to_number(title):
```
|
{"functional": "_inputs = [['A'], ['Z'], ['AA'], ['AZ'], ['BA'], ['CODEWARS'], ['ZZZTOP'], ['OYAJI'], ['LONELINESS'], ['UNFORGIVABLE']]\n_outputs = [[1], [26], [27], [52], [53], [28779382963], [321268054], [7294985], [68400586976949], [79089429845931757]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(title_to_number(*i), o[0])"}
| 128
| 280
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
A certain bug's home is on the x-axis at position x. Help them get there from position 0.
The bug jumps according to the following rules:
It can jump exactly a positions forward (to the right).
It can jump exactly b positions backward (to the left).
It cannot jump backward twice in a row.
It cannot jump to any forbidden positions.
The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.
Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.
Please complete the following python code precisely:
```python
class Solution:
def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9) == 3\n assert candidate(forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11) == -1\n assert candidate(forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7) == 2\n\n\ncheck(Solution().minimumJumps)"}
| 221
| 147
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.
An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.
A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.
For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).
Please complete the following python code precisely:
```python
class Solution:
def findLUSlength(self, strs: List[str]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(strs = [\"aba\",\"cdc\",\"eae\"]) == 3\n assert candidate(strs = [\"aaa\",\"aaa\",\"aa\"]) == -1\n\n\ncheck(Solution().findLUSlength)"}
| 191
| 60
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a 0-indexed integer array nums of even length.
As long as nums is not empty, you must repetitively:
Find the minimum number in nums and remove it.
Find the maximum number in nums and remove it.
Calculate the average of the two removed numbers.
The average of two numbers a and b is (a + b) / 2.
For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.
Return the number of distinct averages calculated using the above process.
Note that when there is a tie for a minimum or maximum number, any can be removed.
Please complete the following python code precisely:
```python
class Solution:
def distinctAverages(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [4,1,4,0,3,5]) == 2\n assert candidate(nums = [1,100]) == 1\n\n\ncheck(Solution().distinctAverages)"}
| 183
| 58
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
A swap is defined as taking two distinct positions in an array and swapping the values in them.
A circular array is defined as an array where we consider the first element and the last element to be adjacent.
Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.
Please complete the following python code precisely:
```python
class Solution:
def minSwaps(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [0,1,0,1,1,0,0]) == 1\n assert candidate(nums = [0,1,1,1,0,0,1,1,0]) == 2\n assert candidate(nums = [1,1,0,0,1]) == 0\n\n\ncheck(Solution().minSwaps)"}
| 119
| 92
|
coding
|
Solve the programming task below in a Python markdown code block.
You have two arrays A and B of size N and M respectively. You have to merge both the arrays to form a new array C of size N + M (the relative order of elements in the original arrays A and B should not change in the array C).
For e.g. if A = [{\color{blue}1}, {\color{blue}2}, {\color{blue}7} ] and B = [{\color{red}3}, {\color{red}6}, {\color{red}5}], one possible way to merge them to form C is: C = [{\color{blue}1}, {\color{red}3}, {\color{red}6}, {\color{blue}2}, {\color{red}5}, {\color{blue}7}].
Maximize the length of longest non-decreasing subsequence of the merged array C.
As a reminder, a non-decreasing subsequence of some array X is a sequence of indices i_{1}, i_{2}, ..., i_{k}, such that i_{1} < i_{2} < ... < i_{k} and X_{i_{1}} ≤ X_{i_{2}} ≤ ... ≤ X_{i_{k}}
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains two integers N and M - the size of the array A and B respectively.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \dots, A_{N} denoting the array A.
- The third line of each test case contains M space-separated integers B_{1}, B_{2}, \dots, B_{M} denoting the array B.
------ Output Format ------
For each test case, output the maximum possible length of longest non-decreasing subsequence in the merged array.
------ Constraints ------
$1 ≤ T ≤ 1000$
$1 ≤ N, M ≤ 10^{5}$
$1 ≤ A_{i}, B_{i} ≤ 10^{9}$
- It is guaranteed that the sum of $N$ over all test cases does not exceed $4 \cdot 10^{5}$.
- It is guaranteed that the sum of $M$ over all test cases does not exceed $4 \cdot 10^{5}$.
----- Sample Input 1 ------
2
3 2
6 4 5
1 3
2 3
1 3
2 2 4
----- Sample Output 1 ------
4
5
----- explanation 1 ------
Test Case-1: We can merge the arrays in the following way: $C = [{\color{blue}6}, {\color{red}1}, {\color{red}3}, {\color{blue}4}, {\color{blue}5}]$. The length of longest non-decreasing subsequence in this case is $4$.
Test Case-2: We can merge the arrays in the following way: $C = [{\color{blue}1}, {\color{red}2}, {\color{red}2}, {\color{blue}3}, {\color{red}4}]$. The length of longest non-decreasing subsequence in this case is $5$.
|
{"inputs": ["2\n3 2\n6 4 5\n1 3\n2 3\n1 3\n2 2 4\n"], "outputs": ["4\n5\n"]}
| 715
| 44
|
coding
|
Solve the programming task below in a Python markdown code block.
Since most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games!
Since you are so curious about Bitland, I'll give you the chance of peeking at one of these games.
BitLGM and BitAryo are playing yet another of their crazy-looking genius-needed Bitlandish games. They've got a sequence of n non-negative integers a_1, a_2, ..., a_{n}. The players make moves in turns. BitLGM moves first. Each player can and must do one of the two following actions in his turn:
Take one of the integers (we'll denote it as a_{i}). Choose integer x (1 ≤ x ≤ a_{i}). And then decrease a_{i} by x, that is, apply assignment: a_{i} = a_{i} - x. Choose integer x $(1 \leq x \leq \operatorname{min}_{i = 1} a_{i})$. And then decrease all a_{i} by x, that is, apply assignment: a_{i} = a_{i} - x, for all i.
The player who cannot make a move loses.
You're given the initial sequence a_1, a_2, ..., a_{n}. Determine who wins, if both players plays optimally well and if BitLGM and BitAryo start playing the described game in this sequence.
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 3).
The next line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} < 300).
-----Output-----
Write the name of the winner (provided that both players play optimally well). Either "BitLGM" or "BitAryo" (without the quotes).
-----Examples-----
Input
2
1 1
Output
BitLGM
Input
2
1 2
Output
BitAryo
Input
3
1 2 1
Output
BitLGM
|
{"inputs": ["1\n6\n", "1\n0\n", "1\n2\n", "1\n1\n", "1\n1\n", "1\n6\n", "1\n2\n", "1\n0\n"], "outputs": ["BitLGM\n", "BitAryo\n", "BitLGM\n", "BitLGM\n", "BitLGM\n", "BitLGM\n", "BitLGM\n", "BitAryo\n"]}
| 465
| 102
|
coding
|
Solve the programming task below in a Python markdown code block.
Tired of the overpopulated world, Miu - The introverted cat visits a new continent in search for a new house.
There are $N$ houses lying on the X-axis.
Their positions are given by $X$$i$ , where $i$ refers to the $i$th house. ( $1 <= i <= N$ )
Each of these positions are pairwise distinct
Miu is supposed to choose one of these houses for herself.
Miu defines a term - The Distance of Peace, as the minimum distance from her house to any other house.
Miu wonders what is maximum Distance of Peace she can obtain. Can you help her?
-----Input:-----
- The first line of the input consists of a single integer $T$, denoting the number of test cases
- The first line of each test case consists of a single integer $N$
- The second line of each test case consists of $N$ space-separated integers
$X$$1$ $X$$2$ $X$$3$ … $X$$N$
-----Output:-----
- For each test case print the answer in a single line, the maximum Distance of Peace Miu can obtain
-----Constraints-----
- 1 <= $T$ <= 100
- 2 <= $N$ <= 105
- -109 <= $X$$i$ <= 109
- Sum of $N$ over all test cases does not exceed 106
-----Subtasks-----
Subtask #1 (30 points):
- $N$ <= 103
Subtask #2 (70 points):
- Original Constraints
-----Sample Input:-----
2
6
7 -1 2 13 -5 15
4
6 10 3 12
-----Sample Output:-----
5
3
-----EXPLANATION:-----
Test Case 1:
The $1$st house has the maximum Distance of Peace, which is from the $3$rd house:
$| 7 - 2 | = 5$
Hence, the answer is $5$
|
{"inputs": ["2\n6\n7 -1 2 13 -5 15\n4\n6 10 3 12"], "outputs": ["5\n3"]}
| 460
| 42
|
coding
|
Solve the programming task below in a Python markdown code block.
Write a function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum.
Assume that the input n will always be a positive integer.
Examples:
```python
sum_cubes(2)
> 9
# sum of the cubes of 1 and 2 is 1 + 8
```
Also feel free to reuse/extend the following starter code:
```python
def sum_cubes(n):
```
|
{"functional": "_inputs = [[1], [2], [3], [4], [10], [123]]\n_outputs = [[1], [9], [36], [100], [3025], [58155876]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(sum_cubes(*i), o[0])"}
| 110
| 201
|
coding
|
Solve the programming task below in a Python markdown code block.
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.
Input
The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.
Output
Print "YES", if the dwarves belong to the same race. Otherwise, print "NO".
Examples
Input
ab
ba
Output
YES
Input
aa
ab
Output
NO
Note
* First example: you can simply swap two letters in string "ab". So we get "ba".
* Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".
|
{"inputs": ["a\nz\n", "b\ng\n", "a\ng\n", "a\nza\n", "ba\na\n", "a\naa\n", "a\nab\n", "`\nza\n"], "outputs": ["NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
| 339
| 86
|
coding
|
Solve the programming task below in a Python markdown code block.
## Description
Your job is to create a simple password validation function, as seen on many websites.
The rules for a valid password are as follows:
- There needs to be at least 1 uppercase letter.
- There needs to be at least 1 lowercase letter.
- There needs to be at least 1 number.
- The password needs to be at least 8 characters long.
You are permitted to use any methods to validate the password.
## Examples:
### Extra info
- You will only be passed strings.
- The string can contain any standard keyboard character.
- Accepted strings can be any length, as long as they are 8 characters or more.
Also feel free to reuse/extend the following starter code:
```python
def password(string):
```
|
{"functional": "_inputs = [['Abcd1234'], ['Abcd123'], ['abcd1234'], ['AbcdefGhijKlmnopQRsTuvwxyZ1234567890'], ['ABCD1234'], ['Ab1!@#$%^&*()-_+={}[]|\\\\:;?/>.<,'], ['!@#$%^&*()-_+={}[]|\\\\:;?/>.<,'], [''], [' aA1----'], ['4aA1----']]\n_outputs = [[True], [False], [False], [True], [False], [True], [False], [False], [True], [True]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(password(*i), o[0])"}
| 168
| 293
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$, consisting of lowercase Latin letters. While there is at least one character in the string $s$ that is repeated at least twice, you perform the following operation:
you choose the index $i$ ($1 \le i \le |s|$) such that the character at position $i$ occurs at least two times in the string $s$, and delete the character at position $i$, that is, replace $s$ with $s_1 s_2 \ldots s_{i-1} s_{i+1} s_{i+2} \ldots s_n$.
For example, if $s=$"codeforces", then you can apply the following sequence of operations:
$i=6 \Rightarrow s=$"codefrces";
$i=1 \Rightarrow s=$"odefrces";
$i=7 \Rightarrow s=$"odefrcs";
Given a given string $s$, find the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string become unique.
A string $a$ of length $n$ is lexicographically less than a string $b$ of length $m$, if:
there is an index $i$ ($1 \le i \le \min(n, m)$) such that the first $i-1$ characters of the strings $a$ and $b$ are the same, and the $i$-th character of the string $a$ is less than $i$-th character of string $b$;
or the first $\min(n, m)$ characters in the strings $a$ and $b$ are the same and $n < m$.
For example, the string $a=$"aezakmi" is lexicographically less than the string $b=$"aezus".
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow.
Each test case is characterized by a string $s$, consisting of lowercase Latin letters ($1 \le |s| \le 2 \cdot 10^5$).
It is guaranteed that the sum of the lengths of the strings in all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string become unique.
-----Examples-----
Input
6
codeforces
aezakmi
abacaba
convexhull
swflldjgpaxs
myneeocktxpqjpz
Output
odfrces
ezakmi
cba
convexhul
wfldjgpaxs
myneocktxqjpz
-----Note-----
None
|
{"inputs": ["6\ncodeforces\naezakmi\nabacaba\nconvexhull\nswflldjgpaxs\nmyneeocktxpqjpz\n", "6\nsecrofedoc\naezakmi\nabacaba\nconvexhull\nswflldjgpaxs\nmyneeocktxpqjpz\n", "6\nsecrofedoc\naezakmi\nabacaba\nconvexhull\nswflldagpjxs\nmyneeocktxpqjpz\n", "6\ncodeforces\naezakmi\nabacabb\nconvexhull\nswflldjgpaxs\nmyneeocktxpqjpz\n", "6\nsecrofedoc\naezakmi\nabacaba\nlluhxevnoc\nswflldjgpaxs\nmyneeocktxpqjpz\n", "6\nsecrofedoc\naezakmi\nabacaba\nconvexhull\nswflldagpjxs\nmxneeocktxpqjpz\n", "6\ncodeforces\naezakmi\nabacabb\nconvexhull\nswflldjgpaxs\nmyneeodktxpqjpz\n", "6\nsecrofedoc\naezakni\nabacaba\nlluhxevnoc\nswflldjgpaxs\nmyneeocktxpqjpz\n"], "outputs": ["odfrces\nezakmi\ncba\nconvexhul\nwfldjgpaxs\nmyneocktxqjpz\n", "srofedc\nezakmi\ncba\nconvexhul\nwfldjgpaxs\nmyneocktxqjpz\n", "srofedc\nezakmi\ncba\nconvexhul\nwfldagpjxs\nmyneocktxqjpz\n", "odfrces\nezakmi\ncab\nconvexhul\nwfldjgpaxs\nmyneocktxqjpz\n", "srofedc\nezakmi\ncba\nluhxevnoc\nwfldjgpaxs\nmyneocktxqjpz\n", "srofedc\nezakmi\ncba\nconvexhul\nwfldagpjxs\nmxneocktqjpz\n", "odfrces\nezakmi\ncab\nconvexhul\nwfldjgpaxs\nmyneodktxqjpz\n", "srofedc\nezakni\ncba\nluhxevnoc\nwfldjgpaxs\nmyneocktxqjpz\n"]}
| 612
| 587
|
coding
|
Solve the programming task below in a Python markdown code block.
A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:
* $insert(S, k)$: insert an element $k$ into the set $S$
* $extractMax(S)$: remove and return the element of $S$ with the largest key
Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$. The priority queue manages a set of integers, which are also keys for the priority.
Constraints
* The number of operations $\leq 2,000,000$
* $0 \leq k \leq 2,000,000,000$
Input
Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.
The input ends with "end" operation.
Output
For each "extract" operation, print the element extracted from the priority queue $S$ in a line.
Example
Input
insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end
Output
8
10
11
2
|
{"inputs": ["insert 8\ninsert 0\nextract\ninsert 4\nextract\ninsert 9\nextract\nextract\nend", "insert 8\ninsert 0\nextract\ninsert 5\nextract\ninsert 2\nextract\nextract\nend", "insert 8\ninsert 0\nextract\ninsert 7\nextract\ninsert 9\nextract\nextract\nend", "insert 8\ninsert 1\nextract\ninsert 5\nextract\ninsert 2\nextract\nextract\nend", "insert 0\ninsert 0\nextract\ninsert 7\nextract\ninsert 9\nextract\nextract\nend", "insert 5\ninsert 1\nextract\ninsert 5\nextract\ninsert 2\nextract\nextract\nend", "insert 8\ninsert 2\nextract\ninsert 8\nextract\ninsert 4\nextract\nextract\nend", "insert 8\ninsert 0\nextract\ninsert 0\nextract\ninsert 6\nextract\nextract\nend"], "outputs": ["8\n4\n9\n0\n", "8\n5\n2\n0\n", "8\n7\n9\n0\n", "8\n5\n2\n1\n", "0\n7\n9\n0\n", "5\n5\n2\n1\n", "8\n8\n4\n2\n", "8\n0\n6\n0\n"]}
| 303
| 302
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Please complete the following python code precisely:
```python
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
```
|
{"functional": "def check(candidate):\n assert candidate(s = \"leetcode\", wordDict = [\"leet\",\"code\"]) == True\n assert candidate(s = \"applepenapple\", wordDict = [\"apple\",\"pen\"]) == True\n assert candidate(s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]) == False\n\n\ncheck(Solution().wordBreak)"}
| 101
| 92
|
coding
|
Solve the programming task below in a Python markdown code block.
When provided with a String, capitalize all vowels
For example:
Input : "Hello World!"
Output : "HEllO WOrld!"
Note: Y is not a vowel in this kata.
Also feel free to reuse/extend the following starter code:
```python
def swap(st):
```
|
{"functional": "_inputs = [['HelloWorld!'], ['Sunday'], ['Codewars'], ['Monday'], ['Friday'], ['abracadabra']]\n_outputs = [['HEllOWOrld!'], ['SUndAy'], ['COdEwArs'], ['MOndAy'], ['FrIdAy'], ['AbrAcAdAbrA']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(swap(*i), o[0])"}
| 73
| 210
|
coding
|
Solve the programming task below in a Python markdown code block.
Nuske has a grid with N rows and M columns of squares. The rows are numbered 1 through N from top to bottom, and the columns are numbered 1 through M from left to right. Each square in the grid is painted in either blue or white. If S_{i,j} is 1, the square at the i-th row and j-th column is blue; if S_{i,j} is 0, the square is white. For every pair of two blue square a and b, there is at most one path that starts from a, repeatedly proceeds to an adjacent (side by side) blue square and finally reaches b, without traversing the same square more than once.
Phantom Thnook, Nuske's eternal rival, gives Q queries to Nuske. The i-th query consists of four integers x_{i,1}, y_{i,1}, x_{i,2} and y_{i,2} and asks him the following: when the rectangular region of the grid bounded by (and including) the x_{i,1}-th row, x_{i,2}-th row, y_{i,1}-th column and y_{i,2}-th column is cut out, how many connected components consisting of blue squares there are in the region?
Process all the queries.
Constraints
* 1 ≤ N,M ≤ 2000
* 1 ≤ Q ≤ 200000
* S_{i,j} is either 0 or 1.
* S_{i,j} satisfies the condition explained in the statement.
* 1 ≤ x_{i,1} ≤ x_{i,2} ≤ N(1 ≤ i ≤ Q)
* 1 ≤ y_{i,1} ≤ y_{i,2} ≤ M(1 ≤ i ≤ Q)
Input
The input is given from Standard Input in the following format:
N M Q
S_{1,1}..S_{1,M}
:
S_{N,1}..S_{N,M}
x_{1,1} y_{i,1} x_{i,2} y_{i,2}
:
x_{Q,1} y_{Q,1} x_{Q,2} y_{Q,2}
Output
For each query, print the number of the connected components consisting of blue squares in the region.
Examples
Input
3 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4
Output
3
2
2
2
Input
5 5 6
11010
01110
10101
11101
01010
1 1 5 5
1 2 4 5
2 3 3 4
3 3 3 3
3 1 3 5
1 1 3 4
Output
3
2
1
1
3
2
|
{"inputs": ["3 4 4\n1101\n0110\n1101\n1 1 3 4\n1 1 3 1\n2 2 3 4\n1 2 3 4", "3 4 4\n1101\n0110\n1101\n1 1 3 4\n2 1 3 1\n2 2 3 4\n1 2 2 4", "3 4 4\n1101\n0110\n1101\n1 1 3 4\n1 1 3 1\n2 2 3 4\n2 2 3 4", "3 4 4\n1101\n0110\n1101\n2 1 3 4\n2 1 3 1\n2 2 3 4\n1 2 2 4", "3 4 4\n1101\n1110\n1101\n1 1 3 4\n1 1 3 1\n2 2 3 4\n2 2 3 4", "3 4 4\n1101\n1110\n1101\n1 1 3 4\n2 1 3 1\n2 1 3 4\n1 2 2 4", "3 4 4\n1101\n0110\n1101\n2 1 3 4\n2 1 3 1\n2 2 3 4\n1 2 3 4", "3 4 4\n1101\n1110\n1101\n1 1 3 4\n1 1 3 2\n2 2 3 4\n2 2 3 4"], "outputs": ["3\n2\n2\n3\n", "3\n1\n2\n2\n", "3\n2\n2\n2\n", "2\n1\n2\n2\n", "1\n1\n2\n2\n", "1\n1\n1\n2\n", "2\n1\n2\n3\n", "1\n-1\n2\n2\n"]}
| 676
| 519
|
coding
|
Solve the programming task below in a Python markdown code block.
How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?
- 0 \leq A_i \leq 9
- There exists some i such that A_i=0 holds.
- There exists some i such that A_i=9 holds.
The answer can be very large, so output it modulo 10^9 + 7.
-----Constraints-----
- 1 \leq N \leq 10^6
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the answer modulo 10^9 + 7.
-----Sample Input-----
2
-----Sample Output-----
2
Two sequences \{0,9\} and \{9,0\} satisfy all conditions.
|
{"inputs": ["0", "3", "5", "7", "4", "6", "9", "8"], "outputs": ["0\n", "54\n", "14670\n", "2531214\n", "974\n", "199262\n", "359376750\n", "30683774\n"]}
| 188
| 95
|
coding
|
Solve the programming task below in a Python markdown code block.
One day, Delta, the dog, got very angry. He has $N$ items with different values, and he decided to destroy a few of them. However, Delta loves his hooman as well. So he only destroyed those items whose Least Significant Bit in binary representation is 0.
Can you help Delta to find the total damage he did so he could make an equally sorry face?
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of Each test case a single integer $N$.
- Next line contains $N$ integers denoting values of items.
-----Output:-----
For each testcase, output in a single line the total damage caused by Delta.
-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^3$
- $1 \leq value \leq 10^3$
-----Sample Input:-----
1
5
1 2 3 4 5
-----Sample Output:-----
6
-----EXPLANATION:-----
Total Damage: $2 + 4 = 6$.
|
{"inputs": ["1\n5\n1 2 3 4 5"], "outputs": ["6"]}
| 262
| 24
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want:
Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2.
The cost of the swap is min(basket1[i],basket2[j]).
Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.
Return the minimum cost to make both the baskets equal or -1 if impossible.
Please complete the following python code precisely:
```python
class Solution:
def minCost(self, basket1: List[int], basket2: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(basket1 = [4,2,2,2], basket2 = [1,4,1,2]) == 1\n assert candidate(basket1 = [2,3,4,1], basket2 = [3,2,5,1]) == -1\n\n\ncheck(Solution().minCost)"}
| 194
| 83
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.