question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Cheesy Cheeseman just got a new monitor! He is happy with it, but he just discovered that his old desktop wallpaper no longer fits. He wants to find a new wallpaper, but does not know which size wallpaper he should be looking for, and alas, he just threw out the new monitor's box. Luckily he remembers the width and the aspect ratio of the monitor from when Bob Mortimer sold it to him. Can you help Cheesy out?
# The Challenge
Given an integer `width` and a string `ratio` written as `WIDTH:HEIGHT`, output the screen dimensions as a string written as `WIDTHxHEIGHT`.
Write your solution by modifying this code:
```python
def find_screen_height(width, ratio):
```
Your solution should implemented in the function "find_screen_height". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.
-----Constraints-----
- 0 \leq x \leq 1
- x is an integer
-----Input-----
Input is given from Standard Input in the following format:
x
-----Output-----
Print 1 if x is equal to 0, or 0 if x is equal to 1.
-----Sample Input-----
1
-----Sample Output-----
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider the number `1176` and its square (`1176 * 1176) = 1382976`. Notice that:
* the first two digits of `1176` form a prime.
* the first two digits of the square `1382976` also form a prime.
* the last two digits of `1176` and `1382976` are the same.
Given two numbers representing a range (`a, b`), how many numbers satisfy this property within that range? (`a <= n < b`)
## Example
`solve(2, 1200) = 1`, because only `1176` satisfies this property within the range `2 <= n < 1200`. See test cases for more examples. The upper bound for the range will not exceed `1,000,000`.
Good luck!
If you like this Kata, please try:
[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
[Alphabet symmetry](https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0)
[Upside down numbers](https://www.codewars.com/kata/59f7597716049833200001eb)
Write your solution by modifying this code:
```python
def solve(a,b):
```
Your solution should implemented in the function "solve". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Phoenix has $n$ coins with weights $2^1, 2^2, \dots, 2^n$. He knows that $n$ is even.
He wants to split the coins into two piles such that each pile has exactly $\frac{n}{2}$ coins and the difference of weights between the two piles is minimized. Formally, let $a$ denote the sum of weights in the first pile, and $b$ denote the sum of weights in the second pile. Help Phoenix minimize $|a-b|$, the absolute value of $a-b$.
-----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.
The first line of each test case contains an integer $n$ ($2 \le n \le 30$; $n$ is even) — the number of coins that Phoenix has.
-----Output-----
For each test case, output one integer — the minimum possible difference of weights between the two piles.
-----Example-----
Input
2
2
4
Output
2
6
-----Note-----
In the first test case, Phoenix has two coins with weights $2$ and $4$. No matter how he divides the coins, the difference will be $4-2=2$.
In the second test case, Phoenix has four coins of weight $2$, $4$, $8$, and $16$. It is optimal for Phoenix to place coins with weights $2$ and $16$ in one pile, and coins with weights $4$ and $8$ in another pile. The difference is $(2+16)-(4+8)=6$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# 'Magic' recursion call depth number
This Kata was designed as a Fork to the one from donaldsebleung Roboscript series with a reference to:
https://www.codewars.com/collections/roboscript
It is not more than an extension of Roboscript infinite "single-" mutual recursion handling to a "multiple-" case.
One can suppose that you have a machine that works through a specific language. It uses the script, which consists of 3 major commands:
- `F` - Move forward by 1 step in the direction that it is currently pointing.
- `L` - Turn "left" (i.e. rotate 90 degrees anticlockwise).
- `R` - Turn "right" (i.e. rotate 90 degrees clockwise).
The number n afterwards enforces the command to execute n times.
To improve its efficiency machine language is enriched by patterns that are containers to pack and unpack the script.
The basic syntax for defining a pattern is as follows:
`pnq`
Where:
- `p` is a "keyword" that declares the beginning of a pattern definition
- `n` is a non-negative integer, which acts as a unique identifier for the pattern (pay attention, it may contain several digits).
- `` is a valid RoboScript code (without the angled brackets)
- `q` is a "keyword" that marks the end of a pattern definition
For example, if you want to define `F2LF2` as a pattern and reuse it later:
```
p333F2LF2q
```
To invoke a pattern, a capital `P` followed by the pattern identifier `(n)` is used:
```
P333
```
It doesn't matter whether the invocation of the pattern or the pattern definition comes first. Pattern definitions should always be parsed first.
```
P333p333P11F2LF2qP333p11FR5Lq
```
# ___Infinite recursion___
As we don't want a robot to be damaged or damaging someone else by becoming uncontrolable when stuck in an infinite loop, it's good to considere this possibility in the programs and to build a compiler that can detect such potential troubles before they actually happen.
* ### Single pattern recursion infinite loop
This is the simplest case, that occurs when the pattern is invoked inside its definition:
p333P333qP333 => depth = 1: P333 -> (P333)
* ### Single mutual recursion infinite loop
Occurs when a pattern calls to unpack the mutual one, which contains a callback to the first:
p1P2qp2P1qP2 => depth = 2: P2 -> P1 -> (P2)
* ### Multiple mutual recursion infinite loop
Occurs within the combo set of mutual callbacks without termination:
p1P2qp2P3qp3P1qP3 => depth = 3: P3 -> P1 -> P2 -> (P3)
* ### No infinite recursion: terminating branch
This happens when the program can finish without encountering an infinite loop. Meaning the depth will be considered 0. Some examples below:
P4p4FLRq => depth = 0
p1P2qp2R5qP1 => depth = 0
p1P2qp2P1q => depth = 0 (no call)
# Task
Your interpreter should be able to analyse infinite recursion profiles in the input program, including multi-mutual cases.
Though, rather than to analyse only the first encountered infinite loop and get stuck in it like the robot would be, your code will have continue deeper in the calls to find the depth of any infinite recursion or terminating call. Then it should return the minimal and the maximal depths encountered, as an array `[min, max]`.
### About the exploration of the different possible branches of the program:
* Consider only patterns that are to be executed:
```
p1P1q => should return [0, 0], there is no execution
p1P2P3qp2P1qp3P1q => similarly [0, 0]
p1P1qP1 => returns [1, 1]
```
* All patterns need to be executed, strictly left to right. Meaning that you may encounter several branches:
```
p1P2P3qp2P1qp3P1qP3 => should return [2, 3]
P3 -> P1 -> P2 -> (P1) depth = 3 (max)
\-> (P3) depth = 2 (min)
```
# Input
* A valid RoboScript program, as string.
* Nested definitions of patterns, such as `p1...p2***q...q` will not be tested, even if that could be of interest as a Roboscript improvement.
* All patterns will have a unique identifier.
* Since the program is valid, you won't encounter calls to undefined pattern either.
# Output
* An array `[min, max]`, giving what are the minimal and the maximal recursion depths encountered.
### Examples
```
p1F2RF2LqP1 => should return [0, 0], no infinite recursion detected
p1F2RP1F2LqP1 => should return [1, 1], infinite recursion detection case
P2p1P2qp2P1q => should return [2, 2], single mutual infinite recursion case
p1P2qP3p2P3qp3P1q => should return [3, 3], twice mutual infinite recursion case
p1P2P1qp2P3qp3P1qP1 => should return [1, 3], mixed infinite recursion case
```
Write your solution by modifying this code:
```python
def magic_call_depth_number(pattern):
```
Your solution should implemented in the function "magic_call_depth_number". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is a string S. Replace every character in S with x and print the result.
-----Constraints-----
- S is a string consisting of lowercase English letters.
- The length of S is between 1 and 100 (inclusive).
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Replace every character in S with x and print the result.
-----Sample Input-----
sardine
-----Sample Output-----
xxxxxxx
Replacing every character in S with x results in xxxxxxx.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer N.
Find the number of the positive divisors of N!, modulo 10^9+7.
-----Constraints-----
- 1≤N≤10^3
-----Input-----
The input is given from Standard Input in the following format:
N
-----Output-----
Print the number of the positive divisors of N!, modulo 10^9+7.
-----Sample Input-----
3
-----Sample Output-----
4
There are four divisors of 3! =6: 1, 2, 3 and 6. Thus, the output should be 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two positive integers $x$ and $y$. You can perform the following operation with $x$: write it in its binary form without leading zeros, add $0$ or $1$ to the right of it, reverse the binary form and turn it into a decimal number which is assigned as the new value of $x$.
For example:
$34$ can be turned into $81$ via one operation: the binary form of $34$ is $100010$, if you add $1$, reverse it and remove leading zeros, you will get $1010001$, which is the binary form of $81$.
$34$ can be turned into $17$ via one operation: the binary form of $34$ is $100010$, if you add $0$, reverse it and remove leading zeros, you will get $10001$, which is the binary form of $17$.
$81$ can be turned into $69$ via one operation: the binary form of $81$ is $1010001$, if you add $0$, reverse it and remove leading zeros, you will get $1000101$, which is the binary form of $69$.
$34$ can be turned into $69$ via two operations: first you turn $34$ into $81$ and then $81$ into $69$.
Your task is to find out whether $x$ can be turned into $y$ after a certain number of operations (possibly zero).
-----Input-----
The only line of the input contains two integers $x$ and $y$ ($1 \le x, y \le 10^{18}$).
-----Output-----
Print YES if you can make $x$ equal to $y$ and NO if you can't.
-----Examples-----
Input
3 3
Output
YES
Input
7 4
Output
NO
Input
2 8
Output
NO
Input
34 69
Output
YES
Input
8935891487501725 71487131900013807
Output
YES
-----Note-----
In the first example, you don't even need to do anything.
The fourth example is described in the statement.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke is buying a bicycle.
The bicycle of his choice does not come with a bell, so he has to buy one separately.
He has very high awareness of safety, and decides to buy two bells, one for each hand.
The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively.
Find the minimum total price of two different bells.
-----Constraints-----
- 1 \leq a,b,c \leq 10000
- a, b and c are integers.
-----Input-----
Input is given from Standard Input in the following format:
a b c
-----Output-----
Print the minimum total price of two different bells.
-----Sample Input-----
700 600 780
-----Sample Output-----
1300
- Buying a 700-yen bell and a 600-yen bell costs 1300 yen.
- Buying a 700-yen bell and a 780-yen bell costs 1480 yen.
- Buying a 600-yen bell and a 780-yen bell costs 1380 yen.
The minimum among these is 1300 yen.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Square Route
Square root
English text is not available in this practice contest.
Millionaire Shinada, who has decided to build a new mansion, is wondering in which city to build the new mansion. To tell the truth, Mr. Shinada is a strange person who likes squares very much, so he wants to live in a city with as many squares as possible.
Mr. Shinada decided to get a list of cities with roads in a grid pattern and count the number of squares formed by the roads in each city. However, the distance between roads is not always constant, so it is difficult to count squares manually. Therefore, I would like you to write a program that counts the number of squares when given information on a grid-shaped road.
Input
The input is composed of multiple data sets, and each data set has the following structure.
> N M
> h1
> h2
> ...
> hN
> w1
> w2
> ...
> wM
Two positive integers N, M (1 ≤ N, M ≤ 1500) are given on the first line. The following N lines h1, h2, ..., hN (1 ≤ hi ≤ 1000) represent the distance between roads in the north-south direction. Where hi is the distance between the i-th road from the north and the i + 1st road from the north. Similarly, the following M lines w1, ..., wM (1 ≤ wi ≤ 1000) represent the distance between roads in the east-west direction. Where wi is the distance between the i-th road from the west and the i + 1st road from the west. The width of the road itself is narrow enough that it does not need to be considered.
First dataset
Figure D-1: First dataset
N = M = 0 indicates the end of the input and is not included in the dataset.
Output
Print the number of squares on one line for each dataset. For example, the first dataset of Sample Input contains 6 squares as shown below, so the output for this dataset is 6.
Squares included in the first dataset
Figure D-2: Squares in the first dataset
Sample Input
3 3
1
1
Four
2
3
1
1 2
Ten
Ten
Ten
0 0
Output for the Sample Input
6
2
Example
Input
3 3
1
1
4
2
3
1
1 2
10
10
10
0 0
Output
6
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A `bouncy number` is a positive integer whose digits neither increase nor decrease. For example, 1235 is an increasing number, 5321 is a decreasing number, and 2351 is a bouncy number. By definition, all numbers under 100 are non-bouncy, and 101 is the first bouncy number.
Determining if a number is bouncy is easy, but counting all bouncy numbers with N digits can be challenging for large values of N. To complete this kata, you must write a function that takes a number N and return the count of bouncy numbers with N digits. For example, a "4 digit" number includes zero-padded, smaller numbers, such as 0001, 0002, up to 9999.
For clarification, the bouncy numbers between 100 and 125 are: 101, 102, 103, 104, 105, 106, 107, 108, 109, 120, and 121.
Write your solution by modifying this code:
```python
def bouncy_count(n):
```
Your solution should implemented in the function "bouncy_count". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese .
Given an array of n non-negative integers: A_{1}, A_{2}, …, A_{N}. Your mission is finding a pair of integers A_{u}, A_{v} (1 ≤ u < v ≤ N) such that (A_{u} and A_{v}) is as large as possible.
And is a bit-wise operation which is corresponding to & in C++ and Java.
------ Input ------
The first line of the input contains a single integer N. The ith line in the next N lines contains the A_{i}.
------ Output ------
Contains a single integer which is the largest value of A_{u} and A_{v} where 1 ≤ u < v ≤ N.
------ Constraints ------
50 points:
$2 ≤ N ≤ 5000$
$0 ≤ A_{i} ≤ 10^{9}$
50 points:
$2 ≤ N ≤ 3 × 10^{5}$
$0 ≤ A_{i} ≤ 10^{9}$
----- Sample Input 1 ------
4
2
4
8
10
----- Sample Output 1 ------
8
----- explanation 1 ------
2 and 4 = 0
2 and 8 = 0
2 and 10 = 2
4 and 8 = 0
4 and 10 = 0
8 and 10 = 8
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For a given sequence of distinct non-negative integers $(b_1, b_2, \dots, b_k)$ we determine if it is good in the following way:
Consider a graph on $k$ nodes, with numbers from $b_1$ to $b_k$ written on them.
For every $i$ from $1$ to $k$: find such $j$ ($1 \le j \le k$, $j\neq i$), for which $(b_i \oplus b_j)$ is the smallest among all such $j$, where $\oplus$ denotes the operation of bitwise XOR ( https://en.wikipedia.org/wiki/Bitwise_operation#XOR ). Next, draw an undirected edge between vertices with numbers $b_i$ and $b_j$ in this graph.
We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers $b_i$ and $b_j$, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence $(0, 1, 5, 2, 6)$ is not good as we cannot reach $1$ from $5$.
However, sequence $(0, 1, 5, 2)$ is good.
You are given a sequence $(a_1, a_2, \dots, a_n)$ of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least $2$, so that the remaining sequence is good.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 200,000$) — length of the sequence.
The second line contains $n$ distinct non-negative integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the elements of the sequence.
-----Output-----
You should output exactly one integer — the minimum possible number of elements to remove in order to make the remaining sequence good.
-----Examples-----
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
-----Note-----
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers $b_i$ and $b_j$, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball.
Bomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.).
Let's number shells from 0 to 2 from left to right. Thus the left shell is assigned number 0, the middle shell is 1 and the right shell is 2. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly n movements were made by the operator and the ball was under shell x at the end. Now he wonders, what was the initial position of the ball?
-----Input-----
The first line of the input contains an integer n (1 ≤ n ≤ 2·10^9) — the number of movements made by the operator.
The second line contains a single integer x (0 ≤ x ≤ 2) — the index of the shell where the ball was found after n movements.
-----Output-----
Print one integer from 0 to 2 — the index of the shell where the ball was initially placed.
-----Examples-----
Input
4
2
Output
1
Input
1
1
Output
0
-----Note-----
In the first sample, the ball was initially placed beneath the middle shell and the operator completed four movements. During the first move operator swapped the left shell and the middle shell. The ball is now under the left shell. During the second move operator swapped the middle shell and the right one. The ball is still under the left shell. During the third move operator swapped the left shell and the middle shell again. The ball is again in the middle. Finally, the operators swapped the middle shell and the right shell. The ball is now beneath the right shell.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have an array of integers (initially empty).
You have to perform $q$ queries. Each query is of one of two types:
"$1$ $x$" — add the element $x$ to the end of the array;
"$2$ $x$ $y$" — replace all occurrences of $x$ in the array with $y$.
Find the resulting array after performing all the queries.
-----Input-----
The first line contains a single integer $q$ ($1 \le q \le 5 \cdot 10^5$) — the number of queries.
Next $q$ lines contain queries (one per line). Each query is of one of two types:
"$1$ $x$" ($1 \le x \le 5 \cdot 10^5$);
"$2$ $x$ $y$" ($1 \le x, y \le 5 \cdot 10^5$).
It's guaranteed that there is at least one query of the first type.
-----Output-----
In a single line, print $k$ integers — the resulting array after performing all the queries, where $k$ is the number of queries of the first type.
-----Examples-----
Input
7
1 3
1 1
2 1 2
1 2
1 1
1 2
2 1 3
Output
3 2 2 3 2
Input
4
1 1
1 2
1 1
2 2 2
Output
1 2 1
Input
8
2 1 4
1 1
1 4
1 2
2 2 4
2 4 3
1 2
2 2 7
Output
1 3 3 7
-----Note-----
In the first example, the array changes as follows:
$[]$ $\rightarrow$ $[3]$ $\rightarrow$ $[3, 1]$ $\rightarrow$ $[3, 2]$ $\rightarrow$ $[3, 2, 2]$ $\rightarrow$ $[3, 2, 2, 1]$ $\rightarrow$ $[3, 2, 2, 1, 2]$ $\rightarrow$ $[3, 2, 2, 3, 2]$.
In the second example, the array changes as follows:
$[]$ $\rightarrow$ $[1]$ $\rightarrow$ $[1, 2]$ $\rightarrow$ $[1, 2, 1]$ $\rightarrow$ $[1, 2, 1]$.
In the third example, the array changes as follows:
$[]$ $\rightarrow$ $[]$ $\rightarrow$ $[1]$ $\rightarrow$ $[1, 4]$ $\rightarrow$ $[1, 4, 2]$ $\rightarrow$ $[1, 4, 4]$ $\rightarrow$ $[1, 3, 3]$ $\rightarrow$ $[1, 3, 3, 2]$ $\rightarrow$ $[1, 3, 3, 7]$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
> I would, if I could,
> If I couldn't how could I?
> I couldn't, without I could, could I?
> Could you, without you could, could ye?
> Could ye? could ye?
> Could you, without you could, could ye?
It is true, as this old rhyme says, that we can only DO what we can DO and we cannot DO what we cannot DO. Changing some of DOs with COUNTs, we have another statement that we can only COUNT what we can DO and we cannot COUNT what we cannot DO, which looks rather false. We could count what we could do as well as we could count what we couldn't do. Couldn't we, if we confine ourselves to finite issues?
Surely we can count, in principle, both what we can do and what we cannot do, if the object space is finite. Yet, sometimes we cannot count in practice what we can do or what we cannot do. Here, you are challenged, in a set of all positive integers up to (and including) a given bound n, to count all the integers that cannot be represented by a formula of the form a*i+b*j, where a and b are given positive integers and i and j are variables ranging over non-negative integers. You are requested to report only the result of the count, i.e. how many integers are not representable. For example, given n = 7, a = 2, b = 5, you should answer 2, since 1 and 3 cannot be represented in a specified form, and the other five numbers are representable as follows:
2 = 2*1 + 5*0, 4 = 2*2 + 5*0, 5 = 2*0 + 5*1,
6 = 2*3 + 5*0, 7 = 2*1 + 5*1.
Input
The input is a sequence of lines. Each line consists of three integers, n, a and b, in this order, separated by a space. The integers n, a and b are all positive and at most one million, except those in the last line. The last line consists of three zeros.
Output
For each input line except the last one, your program should write out a line that contains only the result of the count.
Example
Input
10 2 3
10 2 5
100 5 25
0 0 0
Output
1
2
80
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array.
For example, the array `arr = [0, 1, 2, 5, 1, 0]` has a peak at position `3` with a value of `5` (since `arr[3]` equals `5`).
~~~if-not:php,cpp,java,csharp
The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be `{pos: [], peaks: []}`.
~~~
~~~if:php
The output will be returned as an associative array with two key-value pairs: `'pos'` and `'peaks'`. Both of them should be (non-associative) arrays. If there is no peak in the given array, simply return `['pos' => [], 'peaks' => []]`.
~~~
~~~if:cpp
The output will be returned as an object of type `PeakData` which has two members: `pos` and `peaks`. Both of these members should be `vector`s. If there is no peak in the given array then the output should be a `PeakData` with an empty vector for both the `pos` and `peaks` members.
`PeakData` is defined in Preloaded as follows:
~~~
~~~if:java
The output will be returned as a ``Map>` with two key-value pairs: `"pos"` and `"peaks"`. If there is no peak in the given array, simply return `{"pos" => [], "peaks" => []}`.
~~~
~~~if:csharp
The output will be returned as a `Dictionary>` with two key-value pairs: `"pos"` and `"peaks"`.
If there is no peak in the given array, simply return `{"pos" => new List(), "peaks" => new List()}`.
~~~
Example: `pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3])` should return `{pos: [3, 7], peaks: [6, 3]}` (or equivalent in other languages)
All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.
The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).
Also, beware of plateaus !!! `[1, 2, 2, 2, 1]` has a peak while `[1, 2, 2, 2, 3]` does not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example:
`pickPeaks([1, 2, 2, 2, 1])` returns `{pos: [1], peaks: [2]}` (or equivalent in other languages)
Have fun!
Write your solution by modifying this code:
```python
def pick_peaks(arr):
```
Your solution should implemented in the function "pick_peaks". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.
Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance.
-----Input-----
The first line of the input contains two integers n and k (1 ≤ k < n ≤ 100 000) — the number of rooms in the hotel and the number of cows travelling with Farmer John.
The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are '0', so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in.
-----Output-----
Print the minimum possible distance between Farmer John's room and his farthest cow.
-----Examples-----
Input
7 2
0100100
Output
2
Input
5 1
01010
Output
2
Input
3 2
000
Output
1
-----Note-----
In the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.
In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.
In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
E869120 is initially standing at the origin (0, 0) in a two-dimensional plane.
He has N engines, which can be used as follows:
- When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the coordinates (X + x_i, Y + y_i).
- E869120 can use these engines in any order, but each engine can be used at most once. He may also choose not to use some of the engines.
He wants to go as far as possible from the origin.
Let (X, Y) be his final coordinates. Find the maximum possible value of \sqrt{X^2 + Y^2}, the distance from the origin.
-----Constraints-----
- 1 \leq N \leq 100
- -1 \ 000 \ 000 \leq x_i \leq 1 \ 000 \ 000
- -1 \ 000 \ 000 \leq y_i \leq 1 \ 000 \ 000
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
: :
x_N y_N
-----Output-----
Print the maximum possible final distance from the origin, as a real value.
Your output is considered correct when the relative or absolute error from the true answer is at most 10^{-10}.
-----Sample Input-----
3
0 10
5 -5
-5 -5
-----Sample Output-----
10.000000000000000000000000000000000000000000000000
The final distance from the origin can be 10 if we use the engines in one of the following three ways:
- Use Engine 1 to move to (0, 10).
- Use Engine 2 to move to (5, -5), and then use Engine 3 to move to (0, -10).
- Use Engine 3 to move to (-5, -5), and then use Engine 2 to move to (0, -10).
The distance cannot be greater than 10, so the maximum possible distance is 10.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
At Aizu Riverside Hospital, inpatients walk twice a day for rehabilitation and health promotion. As the number of people trying to recover their physical strength by walking is increasing day by day in order to leave the hospital energetically, the director plans to give a present to the person who walked the longest distance in a day! I launched it.
Number of patients n (1 ≤ n ≤ 10000), each patient's number pi (1 ≤ pi ≤ 10000), first walk distance d1i, second walk distance d2i (0 ≤ d1i, d2i ≤ 5000) Create a program that outputs the number of the patient with the longest total walking distance and the distance. However, it is assumed that no patient walks the same distance in a day.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
p1 d11 d21
p2 d12 d22
::
pn d1n d2n
All inputs are given as integers. The number of datasets does not exceed 50.
Output
For each input dataset, it prints the number of the patient who walked the longest total distance and the distance walked on one line.
Example
Input
5
263 2345 2504
1 3210 1985
5000 1501 4132
10000 503 3107
51 1758 2690
3
345 5000 2396
7 3910 1590
6789 2525 3616
0
Output
5000 5633
345 7396
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Expression Mining
Consider an arithmetic expression built by combining single-digit positive integers with addition symbols `+`, multiplication symbols `*`, and parentheses `(` `)`, defined by the following grammar rules with the start symbol `E`.
E ::= T | E '+' T
T ::= F | T '*' F
F ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '(' E ')'
When such an arithmetic expression is viewed as a string, its substring, that is, a contiguous sequence of characters within the string, may again form an arithmetic expression. Given an integer n and a string s representing an arithmetic expression, let us count the number of its substrings that can be read as arithmetic expressions with values computed equal to n.
Input
The input consists of multiple datasets, each in the following format.
> n
> s
>
A dataset consists of two lines. In the first line, the target value n is given. n is an integer satisfying 1 ≤ n ≤ 109. The string s given in the second line is an arithmetic expression conforming to the grammar defined above. The length of s does not exceed 2×106. The nesting depth of the parentheses in the string is at most 1000.
The end of the input is indicated by a line containing a single zero. The sum of the lengths of s in all the datasets does not exceed 5×106.
Output
For each dataset, output in one line the number of substrings of s that conform to the above grammar and have the value n. The same sequence of characters appearing at different positions should be counted separately.
Sample Input
3
(1+2)*3+3
2
1*1*1+1*1*1
587
1*(2*3*4)+5+((6+7*8))*(9)
0
Output for the Sample Input
4
9
2
Example
Input
3
(1+2)*3+3
2
1*1*1+1*1*1
587
1*(2*3*4)+5+((6+7*8))*(9)
0
Output
4
9
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.
Visitors are more likely to buy a pair of shovels if their total cost ends with several 9s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs 12345 and 37454, their total cost is 49799, it ends with two nines.
You are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other.
-----Input-----
The first line contains a single integer n (2 ≤ n ≤ 10^9) — the number of shovels in Polycarp's shop.
-----Output-----
Print the number of pairs of shovels such that their total cost ends with maximum possible number of nines.
Note that it is possible that the largest number of 9s at the end is 0, then you should count all such ways.
It is guaranteed that for every n ≤ 10^9 the answer doesn't exceed 2·10^9.
-----Examples-----
Input
7
Output
3
Input
14
Output
9
Input
50
Output
1
-----Note-----
In the first example the maximum possible number of nines at the end is one. Polycarp cah choose the following pairs of shovels for that purpose: 2 and 7; 3 and 6; 4 and 5.
In the second example the maximum number of nines at the end of total cost of two shovels is one. The following pairs of shovels suit Polycarp: 1 and 8; 2 and 7; 3 and 6; 4 and 5; 5 and 14; 6 and 13; 7 and 12; 8 and 11; 9 and 10.
In the third example it is necessary to choose shovels 49 and 50, because the sum of their cost is 99, that means that the total number of nines is equal to two, which is maximum possible for n = 50.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last n days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last n days, or not.
-----Input-----
The first line of input contains single integer n (2 ≤ n ≤ 100) — the number of days.
The second line contains a string of length n consisting of only capital 'S' and 'F' letters. If the i-th letter is 'S', then you were in Seattle office on that day. Otherwise you were in San Francisco. The days are given in chronological order, i.e. today is the last day in this sequence.
-----Output-----
Print "YES" if you flew more times from Seattle to San Francisco, and "NO" otherwise.
You can print each letter in any case (upper or lower).
-----Examples-----
Input
4
FSSF
Output
NO
Input
2
SF
Output
YES
Input
10
FFFFFFFFFF
Output
NO
Input
10
SSFFSFFSFF
Output
YES
-----Note-----
In the first example you were initially at San Francisco, then flew to Seattle, were there for two days and returned to San Francisco. You made one flight in each direction, so the answer is "NO".
In the second example you just flew from Seattle to San Francisco, so the answer is "YES".
In the third example you stayed the whole period in San Francisco, so the answer is "NO".
In the fourth example if you replace 'S' with ones, and 'F' with zeros, you'll get the first few digits of π in binary representation. Not very useful information though.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament. For some reasons, the tournament may not be "fair" for all the contestants. That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The structure of the tournament is formally described at the end of this statement.
After each match, there were always one winner and one loser. The last contestant standing was declared the champion.
<image>
Figure: an example of a tournament
For convenience, the contestants were numbered 1 through N. The contestant numbered 1 was the champion, and the contestant numbered i(2 ≦ i ≦ N) was defeated in a match against the contestant numbered a_i.
We will define the depth of the tournament as the maximum number of the matches that must be played in order to win the championship over all the contestants.
Find the minimum possible depth of the tournament.
The formal description of the structure of the tournament is as follows. In the i-th match, one of the following played against each other:
* Two predetermined contestants
* One predetermined contestant and the winner of the j-th match, where j(j<i) was predetermined
* The winner of the j-th match and the winner of the k-th match, where j and k (j,k<i, j ≠ k) were predetermined
Such structure is valid structure of the tournament, if and only if no contestant who has already been defeated in a match will never play in a match, regardless of the outcome of the matches.
Constraints
* 2 ≦ N ≦ 10^5
* 1 ≦ a_i ≦ N(2 ≦ i ≦ N)
* It is guaranteed that the input is consistent (that is, there exists at least one tournament that matches the given information).
Input
The input is given from Standard Input in the following format:
N
a_2
:
a_N
Output
Print the minimum possible depth of the tournament.
Examples
Input
5
1
1
2
4
Output
3
Input
7
1
2
1
3
1
4
Output
3
Input
4
4
4
1
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array $c$ is a subarray of an array $b$ if $c$ 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.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array $[-1, 2, -3]$ is good, as all arrays $[-1]$, $[-1, 2]$, $[-1, 2, -3]$, $[2]$, $[2, -3]$, $[-3]$ have nonzero sums of elements. However, array $[-1, 2, -1, -3]$ isn't good, as his subarray $[-1, 2, -1]$ has sum of elements equal to $0$.
Help Eugene to calculate the number of nonempty good subarrays of a given array $a$.
-----Input-----
The first line of the input contains a single integer $n$ ($1 \le n \le 2 \times 10^5$) — the length of array $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$) — the elements of $a$.
-----Output-----
Output a single integer — the number of good subarrays of $a$.
-----Examples-----
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
-----Note-----
In the first sample, the following subarrays are good: $[1]$, $[1, 2]$, $[2]$, $[2, -3]$, $[-3]$. However, the subarray $[1, 2, -3]$ isn't good, as its subarray $[1, 2, -3]$ has sum of elements equal to $0$.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray $[41, -41, 41]$ isn't good, as its subarray $[41, -41]$ has sum of elements equal to $0$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a rectangular parallelepiped of size A×B×C, built with blocks of size 1×1×1. Snuke will paint each of the A×B×C blocks either red or blue, so that:
* There is at least one red block and at least one blue block.
* The union of all red blocks forms a rectangular parallelepiped.
* The union of all blue blocks forms a rectangular parallelepiped.
Snuke wants to minimize the difference between the number of red blocks and the number of blue blocks. Find the minimum possible difference.
Constraints
* 2≤A,B,C≤10^9
Input
The input is given from Standard Input in the following format:
A B C
Output
Print the minimum possible difference between the number of red blocks and the number of blue blocks.
Examples
Input
3 3 3
Output
9
Input
2 2 4
Output
0
Input
5 3 5
Output
15
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.
Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≤ xi ≤ yi ≤ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.
Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.
Input
The first line contains integers n, m, k (1 ≤ n, m, k ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the initial array.
Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≤ li ≤ ri ≤ n), (0 ≤ di ≤ 105).
Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≤ xi ≤ yi ≤ m).
The numbers in the lines are separated by single spaces.
Output
On a single line print n integers a1, a2, ..., an — the array after executing all the queries. Separate the printed numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
Examples
Input
3 3 3
1 2 3
1 2 1
1 3 2
2 3 4
1 2
1 3
2 3
Output
9 18 17
Input
1 1 1
1
1 1 1
1 1
Output
2
Input
4 3 6
1 2 3 4
1 2 1
2 3 2
3 4 4
1 2
1 3
2 3
1 2
1 3
2 3
Output
5 18 31 20
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Simon has an array a_1, a_2, ..., a_{n}, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers a_{l}, a_{l} + 1, ..., a_{r} are divisible by a_{j}; value r - l takes the maximum value among all pairs for which condition 1 is true;
Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 3·10^5).
The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6).
-----Output-----
Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order.
-----Examples-----
Input
5
4 6 9 3 6
Output
1 3
2
Input
5
1 3 5 7 9
Output
1 4
1
Input
5
2 3 5 7 11
Output
5 0
1 2 3 4 5
-----Note-----
In the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.
In the second sample all numbers are divisible by number 1.
In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In number theory, an **[abundant](https://en.wikipedia.org/wiki/Abundant_number)** number or an **[excessive](https://en.wikipedia.org/wiki/Abundant_number)** number is one for which the sum of it's **[proper divisors](http://mathworld.wolfram.com/ProperDivisor.html)** is greater than the number itself. The integer **12** is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of **16**. The amount by which the sum exceeds the number is the **abundance**. The number **12** has an abundance of **4**, for example. Other initial abundant numbers are : 12, 18, 20, 24, 30, 36, 40, 42, 48, 54 etc . **Infinitely** many **odd** and **even** abundant numbers exist.
As you should have guessed by now, in this kata your function will take a positive integer **h** as range input and return a nested array/list that will contain the following informations-
* Highest available **odd** or **even** abundant number in that range
* It's **abundance**
Examples
--------
A few examples never hurt nobody, right???
```rust
abundant(15) = [[12], [4]]
abundant(19) = [[18], [3]]
abundant(100) = [[100], [17]]
abundant(999) = [[996], [360]]
```
Tips
----
The problem involves some pretty big random numbers. So try to optimize your code for performance as far as you can. And yes, the input argument will always be positive integers. So no need to check there.
Good luck!
Write your solution by modifying this code:
```python
def abundant(h):
```
Your solution should implemented in the function "abundant". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem Statement
Let's consider operations on monochrome images that consist of hexagonal pixels, each of which is colored in either black or white. Because of the shape of pixels, each of them has exactly six neighbors (e.g. pixels that share an edge with it.)
"Filtering" is an operation to determine the color of a pixel from the colors of itself and its six neighbors. Examples of filterings are shown below.
Example 1: Color a pixel in white when all of its neighboring pixels are white. Otherwise the color will not change.
<image>
Performing this operation on all the pixels simultaneously results in "noise canceling," which removes isolated black pixels.
Example 2: Color a pixel in white when its all neighboring pixels are black. Otherwise the color will not change.
<image>
Performing this operation on all the pixels simultaneously results in "edge detection," which leaves only the edges of filled areas.
Example 3: Color a pixel with the color of the pixel just below it, ignoring any other neighbors.
<image>
Performing this operation on all the pixels simultaneously results in "shifting up" the whole image by one pixel.
Applying some filter, such as "noise canceling" and "edge detection," twice to any image yields the exactly same result as if they were applied only once. We call such filters idempotent. The "shifting up" filter is not idempotent since every repeated application shifts the image up by one pixel.
Your task is to determine whether the given filter is idempotent or not.
Input
The input consists of multiple datasets. The number of dataset is less than $100$. Each dataset is a string representing a filter and has the following format (without spaces between digits).
> $c_0c_1\cdots{}c_{127}$
$c_i$ is either '0' (represents black) or '1' (represents white), which indicates the output of the filter for a pixel when the binary representation of the pixel and its neighboring six pixels is $i$. The mapping from the pixels to the bits is as following:
<image>
and the binary representation $i$ is defined as $i = \sum_{j=0}^6{\mathit{bit}_j \times 2^j}$, where $\mathit{bit}_j$ is $0$ or $1$ if the corresponding pixel is in black or white, respectively. Note that the filter is applied on the center pixel, denoted as bit 3.
The input ends with a line that contains only a single "#".
Output
For each dataset, print "yes" in a line if the given filter is idempotent, or "no" otherwise (quotes are for clarity).
Sample Input
00000000111111110000000011111111000000001111111100000000111111110000000011111111000000001111111100000000111111110000000111111111
10000000111111110000000011111111000000001111111100000000111111110000000011111111000000001111111100000000111111110000000011111111
01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101
Output for the Sample Input
yes
yes
no
Example
Input
00000000111111110000000011111111000000001111111100000000111111110000000011111111000000001111111100000000111111110000000111111111
10000000111111110000000011111111000000001111111100000000111111110000000011111111000000001111111100000000111111110000000011111111
01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101
#
Output
yes
yes
no
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
F: Multiplication is fun --Multiplication Is Interesting -
story
Namba, a high school boy, is thinking of giving her a few lines on her birthday. She is a girl who loves multiplication, so Namba wants to give her a sequence that will allow her to enjoy multiplication as much as possible. However, when the calculation result exceeds 2 ^ {20}, her mood suddenly gets worse (normal human beings cannot calculate the huge number of 2 ^ {20}, so she is still quite good. It can be said that he is a generous person). Namba has created a sequence that will allow you to enjoy as many multiplications as possible so as not to upset her, so your job is to create a program that verifies that the sequence is entertaining enough for her. In other words, your job is to create a program that answers the length of the longest subsequence whose total product does not exceed K in a sequence of consecutive subsequences.
problem
There is a non-negative real sequence S = s_1, s_2, ..., s_N and a non-negative real number K of length N. Your job is to find the length of the longest subsequence of S that meets the following conditions: At this time, the length of the subsequence must be 1 or more.
* Satisfy $ \ prod_ {i = \ ell, \ ldots, r} s_i \ leq $ K for consecutive subsequences $ T = s_ \ ell, \ ldots, s_r $ of S.
If there is no subsequence that meets the conditions, output 0.
Input format
The input is given in the following format.
N K
s_1
s_2
$ \ dots $
s_N
The first row gives the length N of the sequence and the upper limit K of the total product of the subsequences. Of the following N rows, the i-th row is given the i-th real number s_i of the non-negative real column S.
Constraint
* 1 \ leq N \ leq 100,000
* 0 \ leq s_i \ leq 2.00
* 0 \ leq K \ leq 1,048,576
* N is an integer, K and s_i are real numbers that do not contain three decimal places.
Output format
Output the length of the longest subsequence in which the total product of the subsequences of S does not exceed K in one row.
Input example 1
6 2.01
1.10
1.44
0.91
2.00
1.12
1.55
Output example 1
3
Input example 2
8 12.22
2.00
2.00
2.00
1.91
2.00
2.00
2.00
0.01
Output example 2
8
Example
Input
6 2.01
1.10
1.44
0.91
2.00
1.12
1.55
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This kata generalizes [Twice Linear](https://www.codewars.com/kata/5672682212c8ecf83e000050). You may want to attempt that kata first.
## Sequence
Consider an integer sequence `U(m)` defined as:
1. `m` is a given non-empty set of positive integers.
2. `U(m)[0] = 1`, the first number is always 1.
3. For each `x` in `U(m)`, and each `y` in `m`, `x * y + 1` must also be in `U(m)`.
4. No other numbers are in `U(m)`.
5. `U(m)` is sorted, with no duplicates.
### Sequence Examples
#### `U(2, 3) = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]`
1 produces 3 and 4, since `1 * 2 + 1 = 3`, and `1 * 3 + 1 = 4`.
3 produces 7 and 10, since `3 * 2 + 1 = 7`, and `3 * 3 + 1 = 10`.
#### `U(5, 7, 8) = [1, 6, 8, 9, 31, 41, 43, 46, 49, 57, 64, 65, 73, 156, 206, ...]`
1 produces 6, 8, and 9.
6 produces 31, 43, and 49.
## Task:
Implement `n_linear` or `nLinear`: given a set of postive integers `m`, and an index `n`, find `U(m)[n]`, the `n`th value in the `U(m)` sequence.
### Tips
* Tests use large n values. Slow algorithms may time-out.
* Tests use large values in the m set. Algorithms which multiply further than neccessary may overflow.
* Linear run time and memory usage is possible.
* How can you build the sequence iteratively, without growing extra data structures?
Write your solution by modifying this code:
```python
def n_linear(m,n):
```
Your solution should implemented in the function "n_linear". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ consisting of $n$ integer numbers.
Let instability of the array be the following value: $\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$.
You have to remove exactly one element from this array to minimize instability of the resulting $(n-1)$-elements array. Your task is to calculate the minimum possible instability.
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 10^5$) — the number of elements in the array $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^5$) — elements of the array $a$.
-----Output-----
Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $a$.
-----Examples-----
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
-----Note-----
In the first example you can remove $7$ then instability of the remaining array will be $3 - 1 = 2$.
In the second example you can remove either $1$ or $100000$ then instability of the remaining array will be $100000 - 100000 = 0$ and $1 - 1 = 0$ correspondingly.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## Overview
Resistors are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. If you did my Resistor Color Codes kata, you wrote a function which took a string containing a resistor's band colors, and returned a string identifying the resistor's ohms and tolerance values.
Well, now you need that in reverse: The previous owner of your "Beyond-Ultimate Raspberry Pi Starter Kit" (as featured in my Fizz Buzz Cuckoo Clock kata) had emptied all the tiny labeled zip-lock bags of components into the box, so that for each resistor you need for a project, instead of looking for text on a label, you need to find one with the sequence of band colors that matches the ohms value you need.
## The resistor color codes
You can see this Wikipedia page for a colorful chart, but the basic resistor color codes are:
0: black, 1: brown, 2: red, 3: orange, 4: yellow, 5: green, 6: blue, 7: violet, 8: gray, 9: white
All resistors have at least three bands, with the first and second bands indicating the first two digits of the ohms value, and the third indicating the power of ten to multiply them by, for example a resistor with a value of 47 ohms, which equals 47 * 10^0 ohms, would have the three bands "yellow violet black".
Most resistors also have a fourth band indicating tolerance -- in an electronics kit like yours, the tolerance will always be 5%, which is indicated by a gold band. So in your kit, the 47-ohm resistor in the above paragraph would have the four bands "yellow violet black gold".
## Your mission
Your function will receive a string containing the ohms value you need, followed by a space and the word "ohms" (to avoid Codewars unicode headaches I'm just using the word instead of the ohms unicode symbol). The way an ohms value is formatted depends on the magnitude of the value:
* For resistors less than 1000 ohms, the ohms value is just formatted as the plain number. For example, with the 47-ohm resistor above, your function would receive the string `"47 ohms"`, and return the string `"yellow violet black gold".
* For resistors greater than or equal to 1000 ohms, but less than 1000000 ohms, the ohms value is divided by 1000, and has a lower-case "k" after it. For example, if your function received the string `"4.7k ohms"`, it would need to return the string `"yellow violet red gold"`.
* For resistors of 1000000 ohms or greater, the ohms value is divided by 1000000, and has an upper-case "M" after it. For example, if your function received the string `"1M ohms"`, it would need to return the string `"brown black green gold"`.
Test case resistor values will all be between 10 ohms and 990M ohms.
## More examples, featuring some common resistor values from your kit
```
"10 ohms" "brown black black gold"
"100 ohms" "brown black brown gold"
"220 ohms" "red red brown gold"
"330 ohms" "orange orange brown gold"
"470 ohms" "yellow violet brown gold"
"680 ohms" "blue gray brown gold"
"1k ohms" "brown black red gold"
"10k ohms" "brown black orange gold"
"22k ohms" "red red orange gold"
"47k ohms" "yellow violet orange gold"
"100k ohms" "brown black yellow gold"
"330k ohms" "orange orange yellow gold"
"2M ohms" "red black green gold"
```
Have fun!
Write your solution by modifying this code:
```python
def encode_resistor_colors(ohms_string):
```
Your solution should implemented in the function "encode_resistor_colors". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are a total of n x n squares, n rows vertically and n columns horizontally. Some squares are marked. Create a program that reads the marked state of each square and displays the length of the side of the largest square consisting of only the unmarked squares as an output.
For example, each dataset is given the following data:
Ten
... * .... **
..........
** .... ** ..
........ *.
.. * .......
..........
. * ........
..........
.... * .. ***
. * .... * ...
One line of input data represents the square of one line. Of the character strings in the input data,. (Period) indicates unmarked squares, and * (asterisk) indicates marked squares.
In the above example, the square indicated by 0 in the figure below is the largest.
... * .... **
..........
** .... ** ..
... 00000 *.
.. * 00000 ..
... 00000 ..
. * .00000 ..
... 00000 ..
.... * .. ***
. * .... * ...
Therefore, if you output 5, the answer will be correct.
If all the squares are marked, output 0.
Input
Multiple datasets are given in the above format. When n is 0, it is the last input. n is 1000 or less. The input data string does not contain any characters other than periods, asterisks, and line breaks. The number of datasets does not exceed 50.
Output
For each dataset, output the length (integer) of the side of the largest square on one line.
Example
Input
10
...*....**
..........
**....**..
........*.
..*.......
..........
.*........
..........
....*..***
.*....*...
10
****.*****
*..*.*....
****.*....
*....*....
*....*****
..........
****.*****
*..*...*..
****...*..
*..*...*..
0
Output
5
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from x = 0 to x = a and back. Moving from the point x = 0 to x = a or from the point x = a to x = 0 is called a bus journey. In total, the bus must make k journeys.
The petrol tank of the bus can hold b liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.
There is a gas station in point x = f. This point is between points x = 0 and x = a. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain b liters of gasoline.
What is the minimum number of times the bus needs to refuel at the point x = f to make k journeys? The first journey starts in the point x = 0.
-----Input-----
The first line contains four integers a, b, f, k (0 < f < a ≤ 10^6, 1 ≤ b ≤ 10^9, 1 ≤ k ≤ 10^4) — the endpoint of the first bus journey, the capacity of the fuel tank of the bus, the point where the gas station is located, and the required number of journeys.
-----Output-----
Print the minimum number of times the bus needs to refuel to make k journeys. If it is impossible for the bus to make k journeys, print -1.
-----Examples-----
Input
6 9 2 4
Output
4
Input
6 10 2 4
Output
2
Input
6 5 4 3
Output
-1
-----Note-----
In the first example the bus needs to refuel during each journey.
In the second example the bus can pass 10 units of distance without refueling. So the bus makes the whole first journey, passes 4 units of the distance of the second journey and arrives at the point with the gas station. Then it can refuel its tank, finish the second journey and pass 2 units of distance from the third journey. In this case, it will again arrive at the point with the gas station. Further, he can refill the tank up to 10 liters to finish the third journey and ride all the way of the fourth journey. At the end of the journey the tank will be empty.
In the third example the bus can not make all 3 journeys because if it refuels during the second journey, the tanks will contain only 5 liters of gasoline, but the bus needs to pass 8 units of distance until next refueling.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
Given two integers `a` and `b`, return the sum of the numerator and the denominator of the reduced fraction `a/b`.
# Example
For `a = 2, b = 4`, the result should be `3`
Since `2/4 = 1/2 => 1 + 2 = 3`.
For `a = 10, b = 100`, the result should be `11`
Since `10/100 = 1/10 => 1 + 10 = 11`.
For `a = 5, b = 5`, the result should be `2`
Since `5/5 = 1/1 => 1 + 1 = 2`.
# Input/Output
- `[input]` integer `a`
The numerator, `1 ≤ a ≤ 2000`.
- `[input]` integer `b`
The denominator, `1 ≤ b ≤ 2000`.
- `[output]` an integer
The sum of the numerator and the denominator of the reduces fraction.
Write your solution by modifying this code:
```python
def fraction(a, b):
```
Your solution should implemented in the function "fraction". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≤ j ≤ m - n. Suppose, c_{i} = a_{i} - b_{i} + j. Then f(j) = |c_1 - c_2 + c_3 - c_4... c_{n}|. More formally, $f(j) =|\sum_{i = 1}^{n}(- 1)^{i - 1} *(a_{i} - b_{i + j})|$.
Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid j. They found it a bit easy, so Dr. Evil made their task harder. He will give them q update queries. During each update they should add an integer x_{i} to all elements in a in range [l_{i};r_{i}] i.e. they should add x_{i} to a_{l}_{i}, a_{l}_{i} + 1, ... , a_{r}_{i} and then they should calculate the minimum value of f(j) for all valid j.
Please help Mahmoud and Ehab.
-----Input-----
The first line contains three integers n, m and q (1 ≤ n ≤ m ≤ 10^5, 1 ≤ q ≤ 10^5) — number of elements in a, number of elements in b and number of queries, respectively.
The second line contains n integers a_1, a_2, ..., a_{n}. ( - 10^9 ≤ a_{i} ≤ 10^9) — elements of a.
The third line contains m integers b_1, b_2, ..., b_{m}. ( - 10^9 ≤ b_{i} ≤ 10^9) — elements of b.
Then q lines follow describing the queries. Each of them contains three integers l_{i} r_{i} x_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, - 10^9 ≤ x ≤ 10^9) — range to be updated and added value.
-----Output-----
The first line should contain the minimum value of the function f before any update.
Then output q lines, the i-th of them should contain the minimum value of the function f after performing the i-th update .
-----Example-----
Input
5 6 3
1 2 3 4 5
1 2 3 4 5 6
1 1 10
1 1 -9
1 5 -1
Output
0
9
0
0
-----Note-----
For the first example before any updates it's optimal to choose j = 0, f(0) = |(1 - 1) - (2 - 2) + (3 - 3) - (4 - 4) + (5 - 5)| = |0| = 0.
After the first update a becomes {11, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(11 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6) = |9| = 9.
After the second update a becomes {2, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(2 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6)| = |0| = 0.
After the third update a becomes {1, 1, 2, 3, 4} and it's optimal to choose j = 0, f(0) = |(1 - 1) - (1 - 2) + (2 - 3) - (3 - 4) + (4 - 5)| = |0| = 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Print all combinations which can be made by $k$ different elements from $0, 1, ..., n-1$. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a combination is calculated by bitwise OR of the selected elements.
Constraints
* $1 \leq n \leq 18$
* $k \leq n$
Input
The input is given in the following format.
$n \; k$
Output
Print the combinations ordered by their decimal integers. Print a combination in the following format.
$d$: $e_0$ $e_1$ ...
Print ':' after the integer value $d$, then print elements $e_i$ in the combination in ascending order. Separate two adjacency elements by a space character.
Example
Input
5 3
Output
7: 0 1 2
11: 0 1 3
13: 0 2 3
14: 1 2 3
19: 0 1 4
21: 0 2 4
22: 1 2 4
25: 0 3 4
26: 1 3 4
28: 2 3 4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Basic regex tasks. Write a function that takes in a numeric code of any length. The function should check if the code begins with 1, 2, or 3 and return `true` if so. Return `false` otherwise.
You can assume the input will always be a number.
Write your solution by modifying this code:
```python
def validate_code(code):
```
Your solution should implemented in the function "validate_code". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Wilson primes satisfy the following condition.
Let ```P``` represent a prime number.
Then ```((P-1)! + 1) / (P * P)``` should give a whole number.
Your task is to create a function that returns ```true``` if the given number is a Wilson prime.
Write your solution by modifying this code:
```python
def am_i_wilson(n):
```
Your solution should implemented in the function "am_i_wilson". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
- An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
- An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
-----Constraints-----
- All values in input are integers.
- 1 \leq Q \leq 2 \times 10^5
- -10^9 \leq a, b \leq 10^9
- The first query is an update query.
-----Input-----
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
-----Output-----
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
-----Sample Input-----
4
1 4 2
2
1 1 -8
2
-----Sample Output-----
4 2
1 -3
In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.
In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm.
The dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has n students. Dean's office allows i-th student to use the segment (l_{i}, r_{i}) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!
Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (n - 1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.
-----Input-----
The first line contains a positive integer n (1 ≤ n ≤ 100). The (i + 1)-th line contains integers l_{i} and r_{i} (0 ≤ l_{i} < r_{i} ≤ 100) — the endpoints of the corresponding segment for the i-th student.
-----Output-----
On a single line print a single number k, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments.
-----Examples-----
Input
3
0 5
2 8
1 6
Output
1
Input
3
0 10
1 5
7 15
Output
3
-----Note-----
Note that it's not important are clothes drying on the touching segments (e.g. (0, 1) and (1, 2)) considered to be touching or not because you need to find the length of segments.
In the first test sample Alexey may use the only segment (0, 1). In such case his clothes will not touch clothes on the segments (1, 6) and (2, 8). The length of segment (0, 1) is 1.
In the second test sample Alexey may dry his clothes on segments (0, 1) and (5, 7). Overall length of these segments is 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S.
For a non-empty subset T of the set \{1, 2, \ldots , N \}, let us define f(T) as follows:
- f(T) is the number of different non-empty subsets \{x_1, x_2, \ldots , x_k \} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.
Find the sum of f(T) over all 2^N-1 subsets T of \{1, 2, \ldots , N \}. Since the sum can be enormous, print it modulo 998244353.
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 3000
- 1 \leq S \leq 3000
- 1 \leq A_i \leq 3000
-----Input-----
Input is given from Standard Input in the following format:
N S
A_1 A_2 ... A_N
-----Output-----
Print the sum of f(T) modulo 998244353.
-----Sample Input-----
3 4
2 2 4
-----Sample Output-----
6
For each T, the value of f(T) is shown below. The sum of these values is 6.
- f(\{1\}) = 0
- f(\{2\}) = 0
- f(\{3\}) = 1 (One subset \{3\} satisfies the condition.)
- f(\{1, 2\}) = 1 (\{1, 2\})
- f(\{2, 3\}) = 1 (\{3\})
- f(\{1, 3\}) = 1 (\{3\})
- f(\{1, 2, 3\}) = 2 (\{1, 2\}, \{3\})
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A [sequence or a series](http://world.mathigon.org/Sequences), in mathematics, is a string of objects, like numbers, that follow a particular pattern. The individual elements in a sequence are called terms. A simple example is `3, 6, 9, 12, 15, 18, 21, ...`, where the pattern is: _"add 3 to the previous term"_.
In this kata, we will be using a more complicated sequence: `0, 1, 3, 6, 10, 15, 21, 28, ...`
This sequence is generated with the pattern: _"the nth term is the sum of numbers from 0 to n, inclusive"_.
```
[ 0, 1, 3, 6, ...]
0 0+1 0+1+2 0+1+2+3
```
## Your Task
Complete the function that takes an integer `n` and returns a list/array of length `abs(n) + 1` of the arithmetic series explained above. When`n < 0` return the sequence with negative terms.
## Examples
```
5 --> [0, 1, 3, 6, 10, 15]
-5 --> [0, -1, -3, -6, -10, -15]
7 --> [0, 1, 3, 6, 10, 15, 21, 28]
```
Write your solution by modifying this code:
```python
def sum_of_n(n):
```
Your solution should implemented in the function "sum_of_n". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
N cells are arranged in a row. Some of them may contain tokens. You are given a string s that consists of `0`s and `1`s. If the i-th character of s is `1`, the i-th cell (from left) contains a token. Otherwise, it doesn't contain a token.
Snuke wants to perform the following operation as many times as possible. In each operation, he chooses three consecutive cells. Let's call the cells X, Y, Z from left to right. In order for the operation to be valid, both X and Z must contain tokens and Y must not contain a token. Then, he removes these two tokens and puts a new token on Y.
How many operations can he perform if he performs operations in the optimal way?
Constraints
* 1 \leq N \leq 500,000
* |s| = N
* Each character in s is either `0` or `1`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print the answer.
Examples
Input
7
1010101
Output
2
Input
50
10101000010011011110001001111110000101010111100110
Output
10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are $n$ cities and $m$ bidirectional roads in Berland. The $i$-th road connects the cities $x_i$ and $y_i$, and has the speed limit $s_i$. The road network allows everyone to get from any city to any other city.
The Berland Transport Ministry is planning a road reform.
First of all, maintaining all $m$ roads is too costly, so $m - (n - 1)$ roads will be demolished in such a way that the remaining $(n - 1)$ roads still allow to get to any city from any other city. Formally, the remaining roads should represent an undirected tree.
Secondly, the speed limits on the remaining roads might be changed. The changes will be done sequentially, each change is either increasing the speed limit on some road by $1$, or decreasing it by $1$. Since changing the speed limit requires a lot of work, the Ministry wants to minimize the number of changes.
The goal of the Ministry is to have a road network of $(n - 1)$ roads with the maximum speed limit over all roads equal to exactly $k$. They assigned you the task of calculating the minimum number of speed limit changes they have to perform so the road network meets their requirements.
For example, suppose the initial map of Berland looks like that, and $k = 7$:
Then one of the optimal courses of action is to demolish the roads $1$–$4$ and $3$–$4$, and then decrease the speed limit on the road $2$–$3$ by $1$, so the resulting road network looks like that:
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first line of each test case contains three integers $n$, $m$ and $k$ ($2 \le n \le 2 \cdot 10^5$; $n - 1 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2})$; $1 \le k \le 10^9$) — the number of cities, the number of roads and the required maximum speed limit, respectively.
Then $m$ lines follow. The $i$-th line contains three integers $x_i$, $y_i$ and $s_i$ ($1 \le x_i, y_i \le n$; $x_i \ne y_i$; $1 \le s_i \le 10^9$) — the cities connected by the $i$-th road and the speed limit on it, respectively. All roads are bidirectional.
The road network in each test case is connected (that is, it is possible to reach any city from any other city by traveling along the road), and each pair of cities is connected by at most one road.
The sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. Similarly, the sum of $m$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, print one integer — the minimum number of changes the Ministry has to perform so that the maximum speed limit among the remaining $(n - 1)$ roads is exactly $k$.
-----Examples-----
Input
4
4 5 7
4 1 3
1 2 5
2 3 8
2 4 1
3 4 4
4 6 5
1 2 1
1 3 1
1 4 2
2 4 1
4 3 1
3 2 1
3 2 10
1 2 8
1 3 10
5 5 15
1 2 17
3 1 15
2 3 10
1 4 14
2 5 8
Output
1
3
0
0
-----Note-----
The explanation for the example test:
The first test case is described in the problem statement.
In the second test case, the road network initially looks like that:
The Ministry can demolish the roads $1$–$2$, $3$–$2$ and $3$–$4$, and then increase the speed limit on the road $1$–$4$ three times.
In the third test case, the road network already meets all the requirements.
In the fourth test case, it is enough to demolish the road $1$–$2$ so the resulting road network meets the requirements.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Once n people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of n people made an appointment on one of the next n days, and no two persons have an appointment on the same day.
However, the organization workers are very irresponsible about their job, so none of the signed in people was told the exact date of the appointment. The only way to know when people should come is to write some requests to TBO.
The request form consists of m empty lines. Into each of these lines the name of a signed in person can be written (it can be left blank as well). Writing a person's name in the same form twice is forbidden, such requests are ignored. TBO responds very quickly to written requests, but the reply format is of very poor quality — that is, the response contains the correct appointment dates for all people from the request form, but the dates are in completely random order. Responds to all requests arrive simultaneously at the end of the day (each response specifies the request that it answers).
Fortunately, you aren't among these n lucky guys. As an observer, you have the following task — given n and m, determine the minimum number of requests to submit to TBO to clearly determine the appointment date for each person.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Each of the following t lines contains two integers n and m (1 ≤ n, m ≤ 109) — the number of people who have got an appointment at TBO and the number of empty lines in the request form, correspondingly.
Output
Print t lines, each containing an answer for the corresponding test case (in the order they are given in the input) — the minimum number of requests to submit to TBO.
Examples
Input
5
4 1
4 2
7 3
1 1
42 7
Output
3
2
3
0
11
Note
In the first sample, you need to submit three requests to TBO with three different names. When you learn the appointment dates of three people out of four, you can find out the fourth person's date by elimination, so you do not need a fourth request.
In the second sample you need only two requests. Let's number the persons from 1 to 4 and mention persons 1 and 2 in the first request and persons 1 and 3 in the second request. It is easy to see that after that we can clearly determine each person's appointment date regardless of the answers obtained from TBO.
In the fourth sample only one person signed up for an appointment. He doesn't need to submit any requests — his appointment date is tomorrow.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a code that receives an array of numbers or strings, goes one by one through it while taking one value out, leaving one value in, taking, leaving, and back again to the beginning until all values are out.
It's like a circle of people who decide that every second person will leave it, until the last person is there. So if the last element of the array is taken, the first element that's still there, will stay.
The code returns a new re-arranged array with the taken values by their order. The first value of the initial array is always taken.
Examples:
Write your solution by modifying this code:
```python
def yes_no(arr):
```
Your solution should implemented in the function "yes_no". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
Chef likes trees a lot. Today he has an infinte full binary tree (each node has exactly two childs) with special properties.
Chef's tree has the following special properties :
Each node of the tree is either colored red or black.
Root of the tree is black intially.
Both childs of a red colored node are black and both childs of a black colored node are red.
The root of the tree is labelled as 1. For a node labelled v, it's left child is labelled as 2*v and it's right child is labelled as 2*v+1.
Chef wants to fulfill Q queries on this tree. Each query belongs to any of the following three types:
Qi Change color of all red colored nodes to black and all black colored nodes to red.
Qb x y Count the number of black colored nodes on the path from node x to node y (both inclusive).
Qr x y Count the number of red colored nodes on the path from node x to node y (both inclusive).
Help chef accomplishing this task.
------ Input Format ------
First line of the input contains an integer Q denoting the number of queries. Next Q lines of the input contain Q queries (one per line). Each query belongs to one of the three types mentioned above.
------ Output Format ------
For each query of type Qb or Qr, print the required answer.
------ Constraints ------
1≤Q≤10^{5}
1≤x,y≤10^{9}
Scoring
$ Subtask #1: 1≤Q≤100 1≤x,y≤1000 : 27 pts$
$ Subtask #2: 1≤Q≤10^{3} 1≤x,y≤10^{5} : 25 pts$
$ Subtask #3: 1≤Q≤10^{5} 1≤x,y≤10^{9} : 48 pts$
----- Sample Input 1 ------
5
Qb 4 5
Qr 4 5
Qi
Qb 4 5
Qr 4 5
----- Sample Output 1 ------
2
1
1
2
----- explanation 1 ------
With the initial configuration of the tree, Path from node 4 to node 5 is 4->2->5 and color of nodes on the path is B->R->B.
Number of black nodes are 2.
Number of red nodes are 1.
After Query Qi, New configuration of the path from node 4 to node 5 is R->B->R.
Number of black nodes are 1.
Number of red nodes are 2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).
There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.
-----Notes-----
For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.
-----Constraints-----
- 2 \leq N \leq 8
- P and Q are permutations of size N.
-----Input-----
Input is given from Standard Input in the following format:
N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N
-----Output-----
Print |a - b|.
-----Sample Input-----
3
1 3 2
3 1 2
-----Sample Output-----
3
There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
You are a magician. You're going to perform a trick.
You have `b` black marbles and `w` white marbles in your magic hat, and an infinite supply of black and white marbles that you can pull out of nowhere.
You ask your audience to repeatedly remove a pair of marbles from your hat and, for each pair removed, you add one marble to the hat according to the following rule until there is only 1 marble left.
If the marbles of the pair that is removed are of the same color, you add a white marble to the hat. Otherwise, if one is black and one is white, you add a black marble.
Given the initial number of black and white marbles in your hat, your trick is to predict the color of the last marble.
Note: A magician may confuse your eyes, but not your mind ;-)
# Input/Output
- `[input]` integer `b`
Initial number of black marbles in the hat.
`1 <= b <= 10^9`
- `[input]` integer `w`
Initial number of white marbles in the hat.
`1 <= w <= 10^9`
- `[output]` a string
`"Black"` or `"White"` if you can safely predict the color of the last marble. If not, return `"Unsure"`.
Write your solution by modifying this code:
```python
def not_so_random(b,w):
```
Your solution should implemented in the function "not_so_random". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words. [Image]
He ate coffee mix without water again, so right now he's really messed up and can't think.
Your task is to help him by telling him what to type.
-----Input-----
The first and only line of input contains an integer s (0 ≤ s ≤ 99), Tavas's score.
-----Output-----
In the first and only line of output, print a single string consisting only from English lowercase letters and hyphens ('-'). Do not use spaces.
-----Examples-----
Input
6
Output
six
Input
99
Output
ninety-nine
Input
20
Output
twenty
-----Note-----
You can find all you need to know about English numerals in http://en.wikipedia.org/wiki/English_numerals .
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a certain integer ```n```, we need a function ```big_primefac_div()```, that give an array with the highest prime factor and the highest divisor (not equal to n).
Let's see some cases:
```python
big_primefac_div(100) == [5, 50]
big_primefac_div(1969) == [179, 179]
```
If n is a prime number the function will output an empty list:
```python
big_primefac_div(997) == []
```
If ```n``` is an negative integer number, it should be considered the division with tha absolute number of the value.
```python
big_primefac_div(-1800) == [5, 900]
```
If ```n``` is a float type, will be rejected if it has a decimal part with some digits different than 0. The output "The number has a decimal part. No Results". But ```n ``` will be converted automatically to an integer if all the digits of the decimal part are 0.
```python
big_primefac_div(-1800.00) == [5, 900]
big_primefac_div(-1800.1) == "The number has a decimal part. No Results"
```
Optimization and fast algorithms are a key factor to solve this kata.
Happy coding and enjoy it!
Write your solution by modifying this code:
```python
def big_primefac_div(n):
```
Your solution should implemented in the function "big_primefac_div". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An English booklet has been created for publicizing Aizu to the world. When you read it carefully, you found a misnomer (an error in writing) on the last name of Masayuki Hoshina, the lord of the Aizu domain. The booklet says "Hoshino" not "Hoshina".
Your task is to write a program which replace all the words "Hoshino" with "Hoshina". You can assume that the number of characters in a text is less than or equal to 1000.
Input
The input consists of several datasets. There will be the number of datasets n in the first line. There will be n lines. A line consisting of english texts will be given for each dataset.
Output
For each dataset, print the converted texts in a line.
Example
Input
3
Hoshino
Hashino
Masayuki Hoshino was the grandson of Ieyasu Tokugawa.
Output
Hoshina
Hashino
Masayuki Hoshina was the grandson of Ieyasu Tokugawa.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.
You, the smartwatch, has found N routes to his home.
If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.
Find the smallest cost of a route that takes not longer than time T.
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 100
- 1 \leq T \leq 1000
- 1 \leq c_i \leq 1000
- 1 \leq t_i \leq 1000
- The pairs (c_i, t_i) are distinct.
-----Input-----
Input is given from Standard Input in the following format:
N T
c_1 t_1
c_2 t_2
:
c_N t_N
-----Output-----
Print the smallest cost of a route that takes not longer than time T.
If there is no route that takes not longer than time T, print TLE instead.
-----Sample Input-----
3 70
7 60
1 80
4 50
-----Sample Output-----
4
- The first route gets him home at cost 7.
- The second route takes longer than time T = 70.
- The third route gets him home at cost 4.
Thus, the cost 4 of the third route is the minimum.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".
Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?
Input
The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 ≤ |s1| ≤ 104, 1 ≤ |s2| ≤ 106).
Output
If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.
Examples
Input
abc
xyz
Output
-1
Input
abcd
dabc
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree.
Input
The first input line contains integer number n (1 ≤ n ≤ 700) — amount of vertices in the tree. The following n - 1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, ai, bi (1 ≤ ai, bi ≤ n). It's guaranteed that the graph described in the input is a tree.
Output
Output the only number — the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
6
Input
8
1 2
1 3
2 4
2 5
3 6
3 7
6 8
Output
18
Input
3
1 2
1 3
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer sequence A of length N and an integer K.
You will perform the following operation on this sequence Q times:
- Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one of them as you like).
Let X and Y be the values of the largest and smallest element removed in the Q operations. You would like X-Y to be as small as possible.
Find the smallest possible value of X-Y when the Q operations are performed optimally.
-----Constraints-----
- 1 \leq N \leq 2000
- 1 \leq K \leq N
- 1 \leq Q \leq N-K+1
- 1 \leq A_i \leq 10^9
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N K Q
A_1 A_2 ... A_N
-----Output-----
Print the smallest possible value of X-Y.
-----Sample Input-----
5 3 2
4 3 1 5 2
-----Sample Output-----
1
In the first operation, whichever contiguous subsequence of length 3 we choose, the minimum element in it is 1.
Thus, the first operation removes A_3=1 and now we have A=(4,3,5,2).
In the second operation, it is optimal to choose (A_2,A_3,A_4)=(3,5,2) as the contiguous subsequence of length 3 and remove A_4=2.
In this case, the largest element removed is 2, and the smallest is 1, so their difference is 2-1=1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something.
Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal k. In other words, $\frac{\sum_{j = 1}^{m} a_{j}}{\sum_{j = 1}^{m} b_{j}} = k$ , where a_{j} is the taste of the j-th chosen fruit and b_{j} is its calories.
Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem — now the happiness of a young couple is in your hands!
Inna loves Dima very much so she wants to make the salad from at least one fruit.
-----Input-----
The first line of the input contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10). The second line of the input contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100) — the fruits' tastes. The third line of the input contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100) — the fruits' calories. Fruit number i has taste a_{i} and calories b_{i}.
-----Output-----
If there is no way Inna can choose the fruits for the salad, print in the single line number -1. Otherwise, print a single integer — the maximum possible sum of the taste values of the chosen fruits.
-----Examples-----
Input
3 2
10 8 1
2 7 1
Output
18
Input
5 3
4 4 4 4 4
2 2 2 2 2
Output
-1
-----Note-----
In the first test sample we can get the total taste of the fruits equal to 18 if we choose fruit number 1 and fruit number 2, then the total calories will equal 9. The condition $\frac{18}{9} = 2 = k$ fulfills, that's exactly what Inna wants.
In the second test sample we cannot choose the fruits so as to follow Inna's principle.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Berland SU holds yet another training contest for its students today. n students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers!
Let students be numbered from 1 to n. Laptop of the i-th student has charge a_i at the beginning of the contest and it uses b_i of charge per minute (i.e. if the laptop has c charge at the beginning of some minute, it becomes c - b_i charge at the beginning of the next minute). The whole contest lasts for k minutes.
Polycarp (the coach of Berland SU) decided to buy a single charger so that all the students would be able to successfully finish the contest. He buys the charger at the same moment the contest starts.
Polycarp can choose to buy the charger with any non-negative (zero or positive) integer power output. The power output is chosen before the purchase, it can't be changed afterwards. Let the chosen power output be x. At the beginning of each minute (from the minute contest starts to the last minute of the contest) he can plug the charger into any of the student's laptops and use it for some integer number of minutes. If the laptop is using b_i charge per minute then it will become b_i - x per minute while the charger is plugged in. Negative power usage rate means that the laptop's charge is increasing. The charge of any laptop isn't limited, it can become infinitely large. The charger can be plugged in no more than one laptop at the same time.
The student successfully finishes the contest if the charge of his laptop never is below zero at the beginning of some minute (from the minute contest starts to the last minute of the contest, zero charge is allowed). The charge of the laptop of the minute the contest ends doesn't matter.
Help Polycarp to determine the minimal possible power output the charger should have so that all the students are able to successfully finish the contest. Also report if no such charger exists.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 2 ⋅ 10^5) — the number of students (and laptops, correspondigly) and the duration of the contest in minutes.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the initial charge of each student's laptop.
The third line contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^7) — the power usage of each student's laptop.
Output
Print a single non-negative integer — the minimal possible power output the charger should have so that all the students are able to successfully finish the contest.
If no such charger exists, print -1.
Examples
Input
2 4
3 2
4 2
Output
5
Input
1 5
4
2
Output
1
Input
1 6
4
2
Output
2
Input
2 2
2 10
3 15
Output
-1
Note
Let's take a look at the state of laptops in the beginning of each minute on the first example with the charger of power 5:
1. charge: [3, 2], plug the charger into laptop 1;
2. charge: [3 - 4 + 5, 2 - 2] = [4, 0], plug the charger into laptop 2;
3. charge: [4 - 4, 0 - 2 + 5] = [0, 3], plug the charger into laptop 1;
4. charge: [0 - 4 + 5, 3 - 2] = [1, 1].
The contest ends after the fourth minute.
However, let's consider the charger of power 4:
1. charge: [3, 2], plug the charger into laptop 1;
2. charge: [3 - 4 + 4, 2 - 2] = [3, 0], plug the charger into laptop 2;
3. charge: [3 - 4, 0 - 2 + 4] = [-1, 2], the first laptop has negative charge, thus, the first student doesn't finish the contest.
In the fourth example no matter how powerful the charger is, one of the students won't finish the contest.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's call an array of non-negative integers $a_1, a_2, \ldots, a_n$ a $k$-extension for some non-negative integer $k$ if for all possible pairs of indices $1 \leq i, j \leq n$ the inequality $k \cdot |i - j| \leq min(a_i, a_j)$ is satisfied. The expansion coefficient of the array $a$ is the maximal integer $k$ such that the array $a$ is a $k$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.
You are given an array of non-negative integers $a_1, a_2, \ldots, a_n$. Find its expansion coefficient.
-----Input-----
The first line contains one positive integer $n$ — the number of elements in the array $a$ ($2 \leq n \leq 300\,000$). The next line contains $n$ non-negative integers $a_1, a_2, \ldots, a_n$, separated by spaces ($0 \leq a_i \leq 10^9$).
-----Output-----
Print one non-negative integer — expansion coefficient of the array $a_1, a_2, \ldots, a_n$.
-----Examples-----
Input
4
6 4 5 5
Output
1
Input
3
0 1 2
Output
0
Input
4
821 500 479 717
Output
239
-----Note-----
In the first test, the expansion coefficient of the array $[6, 4, 5, 5]$ is equal to $1$ because $|i-j| \leq min(a_i, a_j)$, because all elements of the array satisfy $a_i \geq 3$. On the other hand, this array isn't a $2$-extension, because $6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5$ is false.
In the second test, the expansion coefficient of the array $[0, 1, 2]$ is equal to $0$ because this array is not a $1$-extension, but it is $0$-extension.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a board with a 2 \times N grid. Snuke covered the board with N dominoes without overlaps. Here, a domino can cover a 1 \times 2 or 2 \times 1 square.
Then, Snuke decided to paint these dominoes using three colors: red, cyan and green. Two dominoes that are adjacent by side should be painted by different colors. Here, it is not always necessary to use all three colors.
Find the number of such ways to paint the dominoes, modulo 1000000007.
The arrangement of the dominoes is given to you as two strings S_1 and S_2 in the following manner:
* Each domino is represented by a different English letter (lowercase or uppercase).
* The j-th character in S_i represents the domino that occupies the square at the i-th row from the top and j-th column from the left.
Constraints
* 1 \leq N \leq 52
* |S_1| = |S_2| = N
* S_1 and S_2 consist of lowercase and uppercase English letters.
* S_1 and S_2 represent a valid arrangement of dominoes.
Input
Input is given from Standard Input in the following format:
N
S_1
S_2
Output
Print the number of such ways to paint the dominoes, modulo 1000000007.
Examples
Input
3
aab
ccb
Output
6
Input
1
Z
Z
Output
3
Input
52
RvvttdWIyyPPQFFZZssffEEkkaSSDKqcibbeYrhAljCCGGJppHHn
RLLwwdWIxxNNQUUXXVVMMooBBaggDKqcimmeYrhAljOOTTJuuzzn
Output
958681902
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Wilbur the pig is tinkering with arrays again. He has the array a_1, a_2, ..., a_{n} initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements a_{i}, a_{i} + 1, ... , a_{n} or subtract 1 from all elements a_{i}, a_{i} + 1, ..., a_{n}. His goal is to end up with the array b_1, b_2, ..., b_{n}.
Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the array a_{i}. Initially a_{i} = 0 for every position i, so this array is not given in the input.
The second line of the input contains n integers b_1, b_2, ..., b_{n} ( - 10^9 ≤ b_{i} ≤ 10^9).
-----Output-----
Print the minimum number of steps that Wilbur needs to make in order to achieve a_{i} = b_{i} for all i.
-----Examples-----
Input
5
1 2 3 4 5
Output
5
Input
4
1 2 2 1
Output
3
-----Note-----
In the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.
In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a simple code of a function and you would like to know what it will return.
F(N, K, Answer, Operator, A[N]) returns int;
begin
for i=1..K do
for j=1..N do
Answer=(Answer operator A_{j})
return Answer
end
Here N, K, Answer and the value returned by the function F are integers; A is an array of N integers numbered from 1 to N; Operator can be one of the binary operators XOR, AND or OR. If you are not familiar with these terms then better have a look at following articles: XOR, OR, AND.
------ Input ------
The first line of input contains an integer T - the number of test cases in file. Description of each test case consists of three lines. The first one contains three integers N, K and initial Answer. Array A is given in the second line and Operator is situated on the third one. Operators are given as strings, of capital letters. It is guaranteed that there will be no whitespaces before or after Operator.
------ Output ------
Output one line for each test case - the value that is returned by described function with given arguments.
------ Constraints ------
$1≤T≤100
$$1≤N≤1000
$0≤Answer, K, A_{i}≤10^{9}
Operator is one of these: "AND", "XOR", "OR".
----- Sample Input 1 ------
3
3 1 0
1 2 3
XOR
3 1 0
1 2 3
AND
3 1 0
1 2 3
OR
----- Sample Output 1 ------
0
0
3
----- explanation 1 ------
0 xor 1 xor 2 xor 3 = 0
0 and 1 and 2 and 3 = 0
0 or 1 or 2 or 3 = 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...
For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.
Please help Dr. Banner.
-----Input-----
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
-----Output-----
Print Dr.Banner's feeling in one line.
-----Examples-----
Input
1
Output
I hate it
Input
2
Output
I hate that I love it
Input
3
Output
I hate that I love that I hate it
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment n in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom.
<image>
The n-long segment is located at a distance equal exactly to 1 from the castle walls. It can be imaginarily divided into unit segments. On some of the unit segments fire demons are located — no more than one demon per position. Each demon is characterised by his strength - by some positive integer. We can regard the fire demons being idle.
Initially Solomon is positioned on the fortress wall. He can perform the following actions several times in a row:
* "L" — Solomon shifts one unit to the left. This movement cannot be performed on the castle wall.
* "R" — Solomon shifts one unit to the left. This movement cannot be performed if there's no ice block to the right.
* "A" — If there's nothing to the right of Solomon, then Solomon creates an ice block that immediately freezes to the block that Solomon is currently standing on. If there already is an ice block, then Solomon destroys it. At that the ice blocks to the right of the destroyed one can remain but they are left unsupported. Those ice blocks fall down.
Solomon spends exactly a second on each of these actions.
As the result of Solomon's actions, ice blocks' segments fall down. When an ice block falls on a fire demon, the block evaporates and the demon's strength is reduced by 1. When the demons' strength is equal to 0, the fire demon vanishes. The picture below shows how it happens. The ice block that falls on the position with no demon, breaks into lots of tiny pieces and vanishes without hurting anybody.
<image>
Help Solomon destroy all the Fire Lord's army in minimum time.
Input
The first line contains an integer n (1 ≤ n ≤ 1000). The next line contains n numbers, the i-th of them represents the strength of the fire demon standing of the i-th position, an integer from 1 to 100. If there's no demon on the i-th position, then the i-th number equals to 0. It is guaranteed that the input data have at least one fire demon.
Output
Print a string of minimum length, containing characters "L", "R" and "A" — the succession of actions leading to the required result.
If there are several possible answers, print any of them.
Examples
Input
3
1 0 1
Output
ARARARALLLA
Input
3
0 2 0
Output
ARARALAARALA
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0 < r2 < r1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested inside the ring.
The Olympic jury decided that r1 will take one of possible values of x1, x2, ..., xn. It is up to jury to decide which particular value r1 will take. Similarly, the Olympic jury decided that p1 will take one of possible value of y1, y2, ..., ym, and p2 will take a value from list z1, z2, ..., zk.
According to most ancient traditions the ratio between the outer ring mass mout and the inner disk mass min must equal <image>, where A, B are constants taken from ancient books. Now, to start making medals, the jury needs to take values for r1, p1, p2 and calculate the suitable value of r2.
The jury wants to choose the value that would maximize radius r2. Help the jury find the sought value of r2. Value r2 doesn't have to be an integer.
Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.
Input
The first input line contains an integer n and a sequence of integers x1, x2, ..., xn. The second input line contains an integer m and a sequence of integers y1, y2, ..., ym. The third input line contains an integer k and a sequence of integers z1, z2, ..., zk. The last line contains two integers A and B.
All numbers given in the input are positive and do not exceed 5000. Each of the three sequences contains distinct numbers. The numbers in the lines are separated by spaces.
Output
Print a single real number — the sought value r2 with absolute or relative error of at most 10 - 6. It is guaranteed that the solution that meets the problem requirements exists.
Examples
Input
3 1 2 3
1 2
3 3 2 1
1 2
Output
2.683281573000
Input
4 2 3 6 4
2 1 2
3 10 6 8
2 1
Output
2.267786838055
Note
In the first sample the jury should choose the following values: r1 = 3, p1 = 2, p2 = 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Ohgas are a prestigious family based on Hachioji. The head of the family, Mr. Nemochi Ohga, a famous wealthy man, wishes to increase his fortune by depositing his money to an operation company. You are asked to help Mr. Ohga maximize his profit by operating the given money during a specified period.
From a given list of possible operations, you choose an operation to deposit the given fund to. You commit on the single operation throughout the period and deposit all the fund to it. Each operation specifies an annual interest rate, whether the interest is simple or compound, and an annual operation charge. An annual operation charge is a constant not depending on the balance of the fund. The amount of interest is calculated at the end of every year, by multiplying the balance of the fund under operation by the annual interest rate, and then rounding off its fractional part. For compound interest, it is added to the balance of the fund under operation, and thus becomes a subject of interest for the following years. For simple interest, on the other hand, it is saved somewhere else and does not enter the balance of the fund under operation (i.e. it is not a subject of interest in the following years). An operation charge is then subtracted from the balance of the fund under operation. You may assume here that you can always pay the operation charge (i.e. the balance of the fund under operation is never less than the operation charge). The amount of money you obtain after the specified years of operation is called ``the final amount of fund.'' For simple interest, it is the sum of the balance of the fund under operation at the end of the final year, plus the amount of interest accumulated throughout the period. For compound interest, it is simply the balance of the fund under operation at the end of the final year.
Operation companies use C, C++, Java, etc., to perform their calculations, so they pay a special attention to their interest rates. That is, in these companies, an interest rate is always an integral multiple of 0.0001220703125 and between 0.0001220703125 and 0.125 (inclusive). 0.0001220703125 is a decimal representation of 1/8192. Thus, interest rates' being its multiples means that they can be represented with no errors under the double-precision binary representation of floating-point numbers.
For example, if you operate 1000000 JPY for five years with an annual, compound interest rate of 0.03125 (3.125 %) and an annual operation charge of 3000 JPY, the balance changes as follows.
The balance of the fund under operation (at the beginning of year) | Interest| The balance of the fund under operation (at the end of year)
---|---|---
A| B = A × 0.03125 (and rounding off fractions) | A + B - 3000
1000000| 31250| 1028250
1028250| 32132| 1057382
1057382| 33043| 1087425
1087425| 33982| 1118407
1118407| 34950| 1150357
After the five years of operation, the final amount of fund is 1150357 JPY.
If the interest is simple with all other parameters being equal, it looks like:
The balance of the fund under operation (at the beginning of year) | Interest | The balance of the fund under operation (at the end of year) | Cumulative interest
---|---|---|---
A| B = A × 0.03125 (and rounding off fractions)| A - 3000|
1000000| 31250| 997000| 31250
997000| 31156| 994000| 62406
994000| 31062| 991000| 93468
991000| 30968| 988000| 124436
988000| 30875| 985000| 155311
In this case the final amount of fund is the total of the fund under operation, 985000 JPY, and the cumulative interests, 155311 JPY, which is 1140311 JPY.
Input
The input consists of datasets. The entire input looks like:
> the number of datasets (=m)
> 1st dataset
> 2nd dataset
> ...
> m-th dataset
>
The number of datasets, m, is no more than 100. Each dataset is formatted as follows.
> the initial amount of the fund for operation
> the number of years of operation
> the number of available operations (=n)
> operation 1
> operation 2
> ...
> operation n
>
The initial amount of the fund for operation, the number of years of operation, and the number of available operations are all positive integers. The first is no more than 100000000, the second no more than 10, and the third no more than 100.
Each ``operation'' is formatted as follows.
> simple-or-compound annual-interest-rate annual-operation-charge
where simple-or-compound is a single character of either '0' or '1', with '0' indicating simple interest and '1' compound. annual-interest-rate is represented by a decimal fraction and is an integral multiple of 1/8192. annual-operation-charge is an integer not exceeding 100000.
Output
For each dataset, print a line having a decimal integer indicating the final amount of fund for the best operation. The best operation is the one that yields the maximum final amount among the available operations. Each line should not have any character other than this number.
You may assume the final balance never exceeds 1000000000. You may also assume that at least one operation has the final amount of the fund no less than the initial amount of the fund.
Example
Input
4
1000000
5
2
0 0.03125 3000
1 0.03125 3000
6620000
7
2
0 0.0732421875 42307
1 0.0740966796875 40942
39677000
4
4
0 0.0709228515625 30754
1 0.00634765625 26165
0 0.03662109375 79468
0 0.0679931640625 10932
10585000
6
4
1 0.0054931640625 59759
1 0.12353515625 56464
0 0.0496826171875 98193
0 0.0887451171875 78966
Output
1150357
10559683
50796918
20829397
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day consists of minutes 1, 2, ..., z. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.
-----Input-----
The only string contains three integers — n, m and z (1 ≤ n, m, z ≤ 10^4).
-----Output-----
Print single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls.
-----Examples-----
Input
1 1 10
Output
10
Input
1 2 5
Output
2
Input
2 3 9
Output
1
-----Note-----
Taymyr is a place in the north of Russia.
In the first test the artists come each minute, as well as the calls, so we need to kill all of them.
In the second test we need to kill artists which come on the second and the fourth minutes.
In the third test — only the artist which comes on the sixth minute.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string S.
Takahashi can insert the character `A` at any position in this string any number of times.
Can he change S into `AKIHABARA`?
Constraints
* 1 \leq |S| \leq 50
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If it is possible to change S into `AKIHABARA`, print `YES`; otherwise, print `NO`.
Examples
Input
KIHBR
Output
YES
Input
AKIBAHARA
Output
NO
Input
AAKIAHBAARA
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Coffee Vending Machine Problems [Part 1]
You have a vending machine, but it can not give the change back. You decide to implement this functionality. First of all, you need to know the minimum number of coins for this operation (i'm sure you don't want to return 100 pennys instead of 1$ coin).
So, find an optimal number of coins required, if you have unlimited set of coins with given denominations.
Assume all inputs are valid positive integers, and every set of coin denominations has len 4 for simplicity;
Examples:
optimal_number_of_coins(1, [1, 2, 5, 10])
(1 penny) so returns 1
optimal_number_of_coins(5, [1, 2, 5, 10])
(5) so returns 1
optimal_number_of_coins(6, [1, 3, 5, 10])
(3+3 or 5+1) = 6 so returns 2
optimal_number_of_coins(10, [1, 2, 5, 10])
(10) so returns 1
optimal_number_of_coins(12, [1, 3, 5, 10])
(10+1+1) = 12 so returns 3
optimal_number_of_coins(53, [1, 2, 5, 25])
(25+25+2+1) = 53 so returns 4
optimal_number_of_coins(7, [1, 1, 1, 25])
(1+1+1+1+1+1+1) = 7 so returns 7
etc..
Have fun =)
Write your solution by modifying this code:
```python
def optimal_number_of_coins(n, coins):
```
Your solution should implemented in the function "optimal_number_of_coins". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.
Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper.
Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?
Note: uppercase and lowercase letters are considered different.
-----Input-----
Input contains a single line containing a string s (1 ≤ |s| ≤ 10^5) — the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s.
The string s contains lowercase and uppercase English letters, i.e. $s_{i} \in \{a, b, \ldots, z, A, B, \ldots, Z \}$.
-----Output-----
Output a single integer, the answer to the problem.
-----Examples-----
Input
Bulbbasaur
Output
1
Input
F
Output
0
Input
aBddulbasaurrgndgbualdBdsagaurrgndbb
Output
2
-----Note-----
In the first case, you could pick: Bulbbasaur.
In the second case, there is no way to pick even a single Bulbasaur.
In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words "Bulbasaur".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.
Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?
-----Input-----
The only line of the input contains a single integer n (1 ≤ n ≤ 10^{100 000}).
-----Output-----
Print the n-th even-length palindrome number.
-----Examples-----
Input
1
Output
11
Input
10
Output
1001
-----Note-----
The first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem Statement
You want to compete in ICPC (Internet Contest of Point Collection). In this contest, we move around in $N$ websites, numbered $1$ through $N$, within a time limit and collect points as many as possible. We can start and end on any website.
There are $M$ links between the websites, and we can move between websites using these links. You can assume that it doesn't take time to move between websites. These links are directed and websites may have links to themselves.
In each website $i$, there is an advertisement and we can get $p_i$ point(s) by watching this advertisement in $t_i$ seconds. When we start on or move into a website, we can decide whether to watch the advertisement or not. But we cannot watch the same advertisement more than once before using any link in the website, while we can watch it again if we have moved among websites and returned to the website using one or more links, including ones connecting a website to itself. Also we cannot watch the advertisement in website $i$ more than $k_i$ times.
You want to win this contest by collecting as many points as you can. So you decided to compute the maximum points that you can collect within $T$ seconds.
Input
The input consists of multiple datasets. The number of dataset is no more than $60$.
Each dataset is formatted as follows.
> $N$ $M$ $T$
> $p_1$ $t_1$ $k_1$
> :
> :
> $p_N$ $t_N$ $k_N$
> $a_1$ $b_1$
> :
> :
> $a_M$ $b_M$
The first line of each dataset contains three integers $N$ ($1 \le N \le 100$), $M$ ($0 \le M \le 1{,}000$) and $T$ ($1 \le T \le 10{,}000$), which denote the number of websites, the number of links, and the time limit, respectively. All the time given in the input is expressed in seconds.
The following $N$ lines describe the information of advertisements. The $i$-th of them contains three integers $p_i$ ($1 \le p_i \le 10{,}000$), $t_i$ ($1 \le t_i \le 10{,}000$) and $k_i$ ($1 \le k_i \le 10{,}000$), which denote the points of the advertisement, the time required to watch the advertisement, and the maximum number of times you can watch the advertisement in website $i$, respectively.
The following $M$ lines describe the information of links. Each line contains two integers $a_i$ and $b_i$ ($1 \le a_i,b_i \le N$), which mean that we can move from website $a_i$ to website $b_i$ using a link.
The end of input is indicated by a line containing three zeros.
Output
For each dataset, output the maximum points that you can collect within $T$ seconds.
Sample Input
5 4 10
4 3 1
6 4 3
3 2 4
2 2 1
8 5 3
1 2
2 3
3 4
4 5
3 3 1000
1000 1 100
1 7 100
10 9 100
1 2
2 3
3 2
1 0 5
25 25 2
1 0 25
25 25 2
5 5 100
1 1 20
1 1 20
10 1 1
10 1 1
10 1 1
1 2
2 1
3 4
4 5
5 3
3 3 100
70 20 10
50 15 20
90 10 10
1 2
2 2
2 3
0 0 0
Output for the Sample Input
15
2014
0
25
40
390
Example
Input
5 4 10
4 3 1
6 4 3
3 2 4
2 2 1
8 5 3
1 2
2 3
3 4
4 5
3 3 1000
1000 1 100
1 7 100
10 9 100
1 2
2 3
3 2
1 0 5
25 25 2
1 0 25
25 25 2
5 5 100
1 1 20
1 1 20
10 1 1
10 1 1
10 1 1
1 2
2 1
3 4
4 5
5 3
3 3 100
70 20 10
50 15 20
90 10 10
1 2
2 2
2 3
0 0 0
Output
15
2014
0
25
40
390
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya has recently started working as a programmer in the IT city company that develops computer games.
Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.
A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.
The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.
Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.
[Image]
-----Input-----
The only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx^2 + vy^2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c).
-----Output-----
Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10^{ - 9}.
-----Examples-----
Input
8 8 0 2 8 3 4 5
Output
8.000000000000 11.000000000000
4.000000000000 8.000000000000
6.000000000000 8.000000000000
6.000000000000 3.000000000000
10.000000000000 3.000000000000
10.000000000000 8.000000000000
12.000000000000 8.000000000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## Task
**_Given_** *an array of integers* , **_Find_** **_the maximum product_** *obtained from multiplying 2 adjacent numbers in the array*.
____
# Notes
* **_Array/list_** size is *at least 2*.
* **_Array/list_** numbers could be a *mixture of positives, negatives also zeroes* .
___
# Input >> Output Examples
```
adjacentElementsProduct([1, 2, 3]); ==> return 6
```
## **_Explanation_**:
* **_The maximum product_** *obtained from multiplying* ` 2 * 3 = 6 `, and **_they're adjacent numbers in the array_**.
___
```
adjacentElementsProduct([9, 5, 10, 2, 24, -1, -48]); ==> return 50
```
## **_Explanation_**:
**_Max product_** obtained *from multiplying* ``` 5 * 10 = 50 ```.
___
```
adjacentElementsProduct([-23, 4, -5, 99, -27, 329, -2, 7, -921]) ==> return -14
```
## **_Explanation_**:
* **_The maximum product_** *obtained from multiplying* ` -2 * 7 = -14 `, and **_they're adjacent numbers in the array_**.
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
Write your solution by modifying this code:
```python
def adjacent_element_product(array):
```
Your solution should implemented in the function "adjacent_element_product". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.
You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s_1 to city t_1 in at most l_1 hours and get from city s_2 to city t_2 in at most l_2 hours.
Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.
-----Input-----
The first line contains two integers n, m (1 ≤ n ≤ 3000, $n - 1 \leq m \leq \operatorname{min} \{3000, \frac{n(n - 1)}{2} \}$) — the number of cities and roads in the country, respectively.
Next m lines contain the descriptions of the roads as pairs of integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them.
The last two lines contains three integers each, s_1, t_1, l_1 and s_2, t_2, l_2, respectively (1 ≤ s_{i}, t_{i} ≤ n, 0 ≤ l_{i} ≤ n).
-----Output-----
Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1.
-----Examples-----
Input
5 4
1 2
2 3
3 4
4 5
1 3 2
3 5 2
Output
0
Input
5 4
1 2
2 3
3 4
4 5
1 3 2
2 4 2
Output
1
Input
5 4
1 2
2 3
3 4
4 5
1 3 2
3 5 1
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.
A square (x; y) is considered bad, if at least one of the two conditions is fulfilled:
* |x + y| ≡ 0 (mod 2a),
* |x - y| ≡ 0 (mod 2b).
Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).
Input
The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad.
Output
Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).
Examples
Input
2 2 1 0 0 1
Output
1
Input
2 2 10 11 0 1
Output
5
Input
2 4 3 -1 3 7
Output
2
Note
In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass!
On the field, there is a row of n units of grass, each with a sweetness s_i. Farmer John has m cows, each with a favorite sweetness f_i and a hunger value h_i. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner:
* The cows from the left and right side will take turns feeding in an order decided by Farmer John.
* When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats h_i units.
* The moment a cow eats h_i units, it will fall asleep there, preventing further cows from passing it from both directions.
* If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset.
Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them.
Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 10^9+7)? The order in which FJ sends the cows does not matter as long as no cows get upset.
Input
The first line contains two integers n and m (1 ≤ n ≤ 5000, 1 ≤ m ≤ 5000) — the number of units of grass and the number of cows.
The second line contains n integers s_1, s_2, …, s_n (1 ≤ s_i ≤ n) — the sweetness values of the grass.
The i-th of the following m lines contains two integers f_i and h_i (1 ≤ f_i, h_i ≤ n) — the favorite sweetness and hunger value of the i-th cow. No two cows have the same hunger and favorite sweetness simultaneously.
Output
Output two integers — the maximum number of sleeping cows that can result and the number of ways modulo 10^9+7.
Examples
Input
5 2
1 1 1 1 1
1 2
1 3
Output
2 2
Input
5 2
1 1 1 1 1
1 2
1 4
Output
1 4
Input
3 2
2 3 2
3 1
2 1
Output
2 4
Input
5 1
1 1 1 1 1
2 5
Output
0 1
Note
In the first example, FJ can line up the cows as follows to achieve 2 sleeping cows:
* Cow 1 is lined up on the left side and cow 2 is lined up on the right side.
* Cow 2 is lined up on the left side and cow 1 is lined up on the right side.
In the second example, FJ can line up the cows as follows to achieve 1 sleeping cow:
* Cow 1 is lined up on the left side.
* Cow 2 is lined up on the left side.
* Cow 1 is lined up on the right side.
* Cow 2 is lined up on the right side.
In the third example, FJ can line up the cows as follows to achieve 2 sleeping cows:
* Cow 1 and 2 are lined up on the left side.
* Cow 1 and 2 are lined up on the right side.
* Cow 1 is lined up on the left side and cow 2 is lined up on the right side.
* Cow 1 is lined up on the right side and cow 2 is lined up on the left side.
In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.
Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.
-----Constraints-----
- 1≦N≦10^5
- 0≦A_i≦N-1
-----Input-----
The input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
-----Output-----
Print the number of the possible orders in which they were standing, modulo 10^9+7.
-----Sample Input-----
5
2 4 4 0 2
-----Sample Output-----
4
There are four possible orders, as follows:
- 2,1,4,5,3
- 2,5,4,1,3
- 3,1,4,5,2
- 3,5,4,1,2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Chef loves research! Now he is looking for subarray of maximal length with non-zero product.
Chef has an array A with N elements: A1, A2, ..., AN.
Subarray Aij of array A is elements from index i to index j: Ai, Ai+1, ..., Aj.
Product of subarray Aij is product of all its elements (from ith to jth).
-----Input-----
- First line contains sinlge integer N denoting the number of elements.
- Second line contains N space-separated integers A1, A2, ..., AN denoting the elements of array.
-----Output-----
- In a single line print single integer - the maximal length of subarray with non-zero product.
-----Constraints-----
- 1 ≤ N ≤ 100000
- 0 ≤ Ai ≤ 10000
-----Example-----
Input:
6
1 0 2 3 0 4
Output:
2
Input:
1
0
Output:
0
Input:
3
1 0 1
Output:
1
-----Explanation-----
For the first sample subarray is: {2, 3}.
For the second sample there are no subbarays with non-zero product.
For the third sample subbarays is {1}, (the first element, or the third one).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare.
Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.
You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.
Input
The first line contain integer t (1 ≤ t ≤ 20), where t is the number of races. After that all races are described one by one. Every race description start with an integer n (1 ≤ n ≤ 50) on a line of itself, where n is the number of clasified drivers in the given race. After that n lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.
Output
Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.
Examples
Input
3
3
Hamilton
Vettel
Webber
2
Webber
Vettel
2
Hamilton
Vettel
Output
Vettel
Hamilton
Input
2
7
Prost
Surtees
Nakajima
Schumacher
Button
DeLaRosa
Buemi
8
Alonso
Prost
NinoFarina
JimClark
DeLaRosa
Nakajima
Patrese
Surtees
Output
Prost
Prost
Note
It is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Shubham has a binary string $s$. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times: Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
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.
-----Input-----
The first line of the input contains a single integer $t$ $(1\le t \le 100)$ — the number of test cases.
Each of the next $t$ lines contains a binary string $s$ $(1 \le |s| \le 1000)$.
-----Output-----
For every string, output the minimum number of operations required to make it good.
-----Example-----
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
-----Note-----
In test cases $1$, $2$, $5$, $6$ no operations are required since they are already good strings.
For the $3$rd test case: "001" can be achieved by flipping the first character — and is one of the possible ways to get a good string.
For the $4$th test case: "000" can be achieved by flipping the second character — and is one of the possible ways to get a good string.
For the $7$th test case: "000000" can be achieved by flipping the third and fourth characters — and is one of the possible ways to get a good string.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $s$ by '0' or '1' so that the string becomes a palindrome and has exactly $a$ characters '0' and exactly $b$ characters '1'. Note that each of the characters '?' is replaced independently from the others.
A string $t$ of length $n$ is called a palindrome if the equality $t[i] = t[n-i+1]$ is true for all $i$ ($1 \le i \le n$).
For example, if $s=$"01?????0", $a=4$ and $b=4$, then you can replace the characters '?' in the following ways:
"01011010";
"01100110".
For the given string $s$ and the numbers $a$ and $b$, replace all the characters with '?' in the string $s$ by '0' or '1' so that the string becomes a palindrome and has exactly $a$ characters '0' and exactly $b$ characters '1'.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow.
The first line of each test case contains two integers $a$ and $b$ ($0 \le a, b \le 2 \cdot 10^5$, $a + b \ge 1$).
The second line of each test case contains the string $s$ of length $a+b$, consisting of the characters '0', '1', and '?'.
It is guaranteed that the sum of the string lengths of $s$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output:
"-1", if you can't replace all the characters '?' in the string $s$ by '0' or '1' so that the string becomes a palindrome and that it contains exactly $a$ characters '0' and exactly $b$ characters '1';
the string that is obtained as a result of the replacement, otherwise.
If there are several suitable ways to replace characters, you can output any.
-----Examples-----
Input
9
4 4
01?????0
3 3
??????
1 0
?
2 2
0101
2 2
01?0
0 1
0
0 3
1?1
2 2
?00?
4 3
??010?0
Output
01011010
-1
0
-1
0110
-1
111
1001
0101010
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail.
You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.
-----Input-----
The first line contains a single integer k (1 ≤ k ≤ 5) — the number of panels Cucumber boy can press with his one hand.
Next 4 lines contain 4 characters each (digits from 1 to 9, or period) — table of panels. If a digit i was written on the panel, it means the boy has to press that panel in time i. If period was written on the panel, he doesn't have to press that panel.
-----Output-----
Output "YES" (without quotes), if he is able to press all the panels in perfect timing. If not, output "NO" (without quotes).
-----Examples-----
Input
1
.135
1247
3468
5789
Output
YES
Input
5
..1.
1111
..1.
..1.
Output
YES
Input
1
....
12.1
.2..
.2..
Output
NO
-----Note-----
In the third sample boy cannot press all panels in perfect timing. He can press all the panels in timing in time 1, but he cannot press the panels in time 2 in timing with his two hands.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian as well.
Mike is given an undirected graph G of N vertices and M edges. A non-negative integer X_{i} is assigned to the i'th vertex of G, for 1 ≤ i ≤ N.
Mike was asked to assign labels to each edge of the graph so that the following condition is satisfied:
Let's suppose that the j'th edge of G connects vertices U_{j} and V_{j}. Then, a non-negative integer Y_{j} equals to XU_{j} xor XV_{j}.
This challenge was too easy for Mike and he solved it quickly.
The next day, Mike started to worry that he had solved the problem too quickly and had made a lot of mistakes, so he decided to double-check his answers. To his horror, Mike discovered that all the values of X_{i} had been lost!
Mike is a very meticulous person and he doesn't like making mistakes, so he decided to create his own values of X_{i} that still produce the same values of Y_{j}.
Your task is to determine whether it is possible to do so. If it is, you should output the K'th lexicographically valid sequence (X_{1}, X_{2}, ..., X_{N}) that satisfies the above conditions, knowing the structure of G and all the values Y_{j}.
------ Note ------
Maybe some of you aren't familiar with some terms in the statement. Here are some articles that could help you understand the problem correctly:
XOR operation: http://en.wikipedia.org/wiki/Exclusive_{or}
Also, the stack memory size is quite limited on CodeChef, so a deep recursion may lead to the Runtime Error verdict.
------ Input ------
The first line of the input contains the integers N, M and K.
The next M lines describe the edges of G; the j'th line contains three integers U_{j}, V_{j} and Y_{j}.
It's guaranteed that G doesn't contain multiple edges and loops.
------ Output ------
If there is no valid labelling, or less than K valid labellings, the only line of the output should contain -1. Otherwise, the only line of the output should contain N non-negative integers, denoting the K'th lexicographically valid sequence (X_{1}, X_{2}, ..., X_{N}).
It's guaranteed that in the correct sequence all of the values of X_{i} won't exceed the 32-bit signed integer limit.
------ Constraints ------
1 ≤ N ≤ 200,000(2 × 10^{5});
0 ≤ M ≤ 300,000(3 × 10^{5});
1 ≤ K ≤ 1,000,000,000(10^{9});
1 ≤ U_{j} ≠ V_{j} ≤ N;
0 ≤ Y_{j} < 2^{31}.
------ Example ------
Input:
5 4 2
1 2 5
1 3 9
2 4 0
2 5 1
Output:
1 4 8 4 5
------ Explanation ------
The first lexicographically valid sequence is equal to (0, 5, 9, 5, 4);
The second lexicographically valid sequence is equal to (1, 4, 8, 4, 5) - that's the one that should be printed out as the answer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are $n$ persons located on a plane. The $i$-th person is located at the point $(x_i, y_i)$ and initially looks at the point $(u_i, v_i)$.
At the same moment of time, all persons will start to rotate clockwise synchronously with the same angular speed. They will rotate until they do one full $360$-degree turn.
It is said that persons $A$ and $B$ made eye contact if person $A$ looks in person $B$'s direction at the same moment when person $B$ looks in person $A$'s direction. If there is a person $C$ located between persons $A$ and $B$, that will not obstruct $A$ and $B$ from making eye contact. A person can make eye contact with more than one person at the same time.
Calculate the number of pairs of persons that will make eye contact at least once during the rotation (including the initial moment).
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of persons. The following $n$ lines describe persons, each line containing four space-separated integers $x_i, y_i, u_i, v_i$ ($|x_i|, |y_i|, |u_i|, |v_i| \le 10^9$; $x_i \ne u_i$ or $y_i \ne v_i$), where ($x_i, y_i$) are the coordinates of the point where the $i$-th person is located and ($u_i$, $v_i$) are the coordinates of the point that the $i$-th person looks at initially. Each person's location is unique in each test case.
The sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case, print one integer — the number of pairs of persons who will make eye contact at least once during the rotation, including the initial moment.
-----Examples-----
Input
3
2
0 0 0 1
1 0 2 0
3
0 0 1 1
1 1 0 0
1 0 2 0
6
0 0 0 1
1 0 1 2
2 0 2 3
3 0 3 -5
4 0 4 -5
5 0 5 -5
Output
0
1
9
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Selection of Participants of an Experiment
Dr. Tsukuba has devised a new method of programming training. In order to evaluate the effectiveness of this method, he plans to carry out a control experiment. Having two students as the participants of the experiment, one of them will be trained under the conventional method and the other under his new method. Comparing the final scores of these two, he will be able to judge the effectiveness of his method.
It is important to select two students having the closest possible scores, for making the comparison fair. He has a list of the scores of all students who can participate in the experiment. You are asked to write a program which selects two of them having the smallest difference in their scores.
Input
The input consists of multiple datasets, each in the following format.
n
a1 a2 … an
A dataset consists of two lines. The number of students n is given in the first line. n is an integer satisfying 2 ≤ n ≤ 1000. The second line gives scores of n students. ai (1 ≤ i ≤ n) is the score of the i-th student, which is a non-negative integer not greater than 1,000,000.
The end of the input is indicated by a line containing a zero. The sum of n's of all the datasets does not exceed 50,000.
Output
For each dataset, select two students with the smallest difference in their scores, and output in a line (the absolute value of) the difference.
Sample Input
5
10 10 10 10 10
5
1 5 8 9 11
7
11 34 83 47 59 29 70
0
Output for the Sample Input
0
1
5
Example
Input
5
10 10 10 10 10
5
1 5 8 9 11
7
11 34 83 47 59 29 70
0
Output
0
1
5
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi is a teacher responsible for a class of N students.
The students are given distinct student numbers from 1 to N.
Today, all the students entered the classroom at different times.
According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).
From these records, reconstruct the order in which the students entered the classroom.
-----Constraints-----
- 1 \le N \le 10^5
- 1 \le A_i \le N
- A_i \neq A_j (i \neq j)
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 \ldots A_N
-----Output-----
Print the student numbers of the students in the order the students entered the classroom.
-----Sample Input-----
3
2 3 1
-----Sample Output-----
3 1 2
First, student number 3 entered the classroom.
Then, student number 1 entered the classroom.
Finally, student number 2 entered the classroom.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer $n$.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $n$ with $\frac{n}{2}$ if $n$ is divisible by $2$; Replace $n$ with $\frac{2n}{3}$ if $n$ is divisible by $3$; Replace $n$ with $\frac{4n}{5}$ if $n$ is divisible by $5$.
For example, you can replace $30$ with $15$ using the first operation, with $20$ using the second operation or with $24$ using the third operation.
Your task is to find the minimum number of moves required to obtain $1$ from $n$ or say that it is impossible to do it.
You have to answer $q$ independent queries.
-----Input-----
The first line of the input contains one integer $q$ ($1 \le q \le 1000$) — the number of queries.
The next $q$ lines contain the queries. For each query you are given the integer number $n$ ($1 \le n \le 10^{18}$).
-----Output-----
Print the answer for each query on a new line. If it is impossible to obtain $1$ from $n$, print -1. Otherwise, print the minimum number of moves required to do it.
-----Example-----
Input
7
1
10
25
30
14
27
1000000000000000000
Output
0
4
6
6
-1
6
72
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After a long day, Alice and Bob decided to play a little game. The game board consists of $n$ cells in a straight line, numbered from $1$ to $n$, where each cell contains a number $a_i$ between $1$ and $n$. Furthermore, no two cells contain the same number.
A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell $i$ to cell $j$ only if the following two conditions are satisfied: the number in the new cell $j$ must be strictly larger than the number in the old cell $i$ (i.e. $a_j > a_i$), and the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. $|i-j|\bmod a_i = 0$).
Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of numbers.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$). Furthermore, there are no pair of indices $i \neq j$ such that $a_i = a_j$.
-----Output-----
Print $s$ — a string of $n$ characters, where the $i$-th character represents the outcome of the game if the token is initially placed in the cell $i$. If Alice wins, then $s_i$ has to be equal to "A"; otherwise, $s_i$ has to be equal to "B".
-----Examples-----
Input
8
3 6 5 4 2 7 1 8
Output
BAAAABAB
Input
15
3 11 2 5 10 9 7 13 15 8 4 12 6 1 14
Output
ABAAAABBBAABAAB
-----Note-----
In the first sample, if Bob puts the token on the number (not position): $1$: Alice can move to any number. She can win by picking $7$, from which Bob has no move. $2$: Alice can move to $3$ and $5$. Upon moving to $5$, Bob can win by moving to $8$. If she chooses $3$ instead, she wins, as Bob has only a move to $4$, from which Alice can move to $8$. $3$: Alice can only move to $4$, after which Bob wins by moving to $8$. $4$, $5$, or $6$: Alice wins by moving to $8$. $7$, $8$: Alice has no move, and hence she loses immediately.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Factorize a given integer n.
Constraints
* 2 ≤ n ≤ 109
Input
n
An integer n is given in a line.
Output
Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a space before each prime factor.
Examples
Input
12
Output
12: 2 2 3
Input
126
Output
126: 2 3 3 7
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.
Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi < bi + 1 for all i < n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i < n.
Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.
Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.
You have several questions in your mind, compute the answer for each of them.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 200 000) — the number of participants and bids.
Each of the following n lines contains two integers ai and bi (1 ≤ ai ≤ n, 1 ≤ bi ≤ 109, bi < bi + 1) — the number of participant who made the i-th bid and the size of this bid.
Next line contains an integer q (1 ≤ q ≤ 200 000) — the number of question you have in mind.
Each of next q lines contains an integer k (1 ≤ k ≤ n), followed by k integers lj (1 ≤ lj ≤ n) — the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question.
It's guaranteed that the sum of k over all question won't exceed 200 000.
Output
For each question print two integer — the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
Examples
Input
6
1 10
2 100
3 1000
1 10000
2 100000
3 1000000
3
1 3
2 2 3
2 1 2
Output
2 100000
1 10
3 1000
Input
3
1 10
2 100
1 1000
2
2 1 2
2 2 3
Output
0 0
1 10
Note
Consider the first sample:
* In the first question participant number 3 is absent so the sequence of bids looks as follows:
1. 1 10
2. 2 100
3. 1 10 000
4. 2 100 000
Participant number 2 wins with the bid 100 000.
* In the second question participants 2 and 3 are absent, so the sequence of bids looks:
1. 1 10
2. 1 10 000
The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem).
* In the third question participants 1 and 2 are absent and the sequence is:
1. 3 1 000
2. 3 1 000 000
The winner is participant 3 with the bid 1 000.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ consisting of $n$ non-negative integers. You have to choose a non-negative integer $x$ and form a new array $b$ of size $n$ according to the following rule: for all $i$ from $1$ to $n$, $b_i = a_i \oplus x$ ($\oplus$ denotes the operation bitwise XOR).
An inversion in the $b$ array is a pair of integers $i$ and $j$ such that $1 \le i < j \le n$ and $b_i > b_j$.
You should choose $x$ in such a way that the number of inversions in $b$ is minimized. If there are several options for $x$ — output the smallest one.
-----Input-----
First line contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of elements in $a$.
Second line contains $n$ space-separated integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$), where $a_i$ is the $i$-th element of $a$.
-----Output-----
Output two integers: the minimum possible number of inversions in $b$, and the minimum possible value of $x$, which achieves those number of inversions.
-----Examples-----
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
-----Note-----
In the first sample it is optimal to leave the array as it is by choosing $x = 0$.
In the second sample the selection of $x = 14$ results in $b$: $[4, 9, 7, 4, 9, 11, 11, 13, 11]$. It has $4$ inversions:
$i = 2$, $j = 3$; $i = 2$, $j = 4$; $i = 3$, $j = 4$; $i = 8$, $j = 9$.
In the third sample the selection of $x = 8$ results in $b$: $[0, 2, 11]$. It has no inversions.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a_1, a_2, ..., a_{n} will result a new sequence b_1, b_2, ..., b_{n} obtained by the following algorithm: b_1 = a_1, b_{n} = a_{n}, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence. For i = 2, ..., n - 1 value b_{i} is equal to the median of three values a_{i} - 1, a_{i} and a_{i} + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
-----Input-----
The first input line of the input contains a single integer n (3 ≤ n ≤ 500 000) — the length of the initial sequence.
The next line contains n integers a_1, a_2, ..., a_{n} (a_{i} = 0 or a_{i} = 1), giving the initial sequence itself.
-----Output-----
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer — the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space — the resulting sequence itself.
-----Examples-----
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
-----Note-----
In the second sample the stabilization occurs in two steps: $01010 \rightarrow 00100 \rightarrow 00000$, and the sequence 00000 is obviously stable.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.
Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.
Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.
Input
First line of input contains single integer number n (2 ≤ n ≤ 100 000) — number of inflorescences.
Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.
Output
Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.
Examples
Input
3
1 1
Output
1
Input
5
1 2 2 2
Output
3
Input
18
1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4
Output
4
Note
In first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.
In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads.
The following are known about the road network:
- People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.
- Different roads may have had different lengths, but all the lengths were positive integers.
Snuke the archeologist found a table with N rows and N columns, A, in the ruin of Takahashi Kingdom.
He thought that it represented the shortest distances between the cities along the roads in the kingdom.
Determine whether there exists a road network such that for each u and v, the integer A_{u, v} at the u-th row and v-th column of A is equal to the length of the shortest path from City u to City v.
If such a network exist, find the shortest possible total length of the roads.
-----Constraints-----
- 1 \leq N \leq 300
- If i ≠ j, 1 \leq A_{i, j} = A_{j, i} \leq 10^9.
- A_{i, i} = 0
-----Inputs-----
Input is given from Standard Input in the following format:
N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}
...
A_{N, 1} A_{N, 2} ... A_{N, N}
-----Outputs-----
If there exists no network that satisfies the condition, print -1.
If it exists, print the shortest possible total length of the roads.
-----Sample Input-----
3
0 1 3
1 0 2
3 2 0
-----Sample Output-----
3
The network below satisfies the condition:
- City 1 and City 2 is connected by a road of length 1.
- City 2 and City 3 is connected by a road of length 2.
- City 3 and City 1 is not connected by a road.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Now that Chef has finished baking and frosting his cupcakes, it's time to package them. Chef has N cupcakes, and needs to decide how many cupcakes to place in each package. Each package must contain the same number of cupcakes. Chef will choose an integer A between 1 and N, inclusive, and place exactly A cupcakes into each package. Chef makes as many packages as possible. Chef then gets to eat the remaining cupcakes. Chef enjoys eating cupcakes very much. Help Chef choose the package size A that will let him eat as many cupcakes as possible.
-----Input-----
Input begins with an integer T, the number of test cases. Each test case consists of a single integer N, the number of cupcakes.
-----Output-----
For each test case, output the package size that will maximize the number of leftover cupcakes. If multiple package sizes will result in the same number of leftover cupcakes, print the largest such size.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 2 ≤ N ≤ 100000000 (108)
-----Sample Input-----
2
2
5
-----Sample Output-----
2
3
-----Explanation-----
In the first test case, there will be no leftover cupcakes regardless of the size Chef chooses, so he chooses the largest possible size. In the second test case, there will be 2 leftover cupcakes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.