question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.
Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.
Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve 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 All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.
Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "n', where n is the total number of tests.
Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.
The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command.
Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run: all examples are the first several tests having filenames "1", "2", ..., "e", where e is the total number of examples; all other files contain regular tests with filenames "e + 1", "e + 2", ..., "n", where n is the total number of all tests.
-----Input-----
The first line contains single integer n (1 β€ n β€ 10^5) β the number of files with tests.
n lines follow, each describing a file with test. Each line has a form of "name_i type_i", where "name_i" is the filename, and "type_i" equals "1", if the i-th file contains an example test, and "0" if it contains a regular test. Filenames of each file are strings of digits and small English letters with length from 1 to 6 characters. The filenames are guaranteed to be distinct.
-----Output-----
In the first line print the minimum number of lines in Vladimir's script file.
After that print the script file, each line should be "move file_1 file_2", where "file_1" is an existing at the moment of this line being run filename, and "file_2" β is a string of digits and small English letters with length from 1 to 6.
-----Examples-----
Input
5
01 0
2 1
2extra 0
3 1
99 0
Output
4
move 3 1
move 01 5
move 2extra 4
move 99 3
Input
2
1 0
2 1
Output
3
move 1 3
move 2 1
move 3 2
Input
5
1 0
11 1
111 0
1111 1
11111 0
Output
5
move 1 5
move 11 1
move 1111 2
move 111 4
move 11111 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 renowned abstract artist Sasha, drawing inspiration from nowhere, decided to paint a picture entitled "Special Olympics". He justly thought that, if the regular Olympic games have five rings, then the Special ones will do with exactly two rings just fine.
Let us remind you that a ring is a region located between two concentric circles with radii r and R (r < R). These radii are called internal and external, respectively. Concentric circles are circles with centers located at the same point.
Soon a white canvas, which can be considered as an infinite Cartesian plane, had two perfect rings, painted with solid black paint. As Sasha is very impulsive, the rings could have different radii and sizes, they intersect and overlap with each other in any way. We know only one thing for sure: the centers of the pair of rings are not the same.
When Sasha got tired and fell into a deep sleep, a girl called Ilona came into the room and wanted to cut a circle for the sake of good memories. To make the circle beautiful, she decided to cut along the contour.
We'll consider a contour to be a continuous closed line through which there is transition from one color to another (see notes for clarification). If the contour takes the form of a circle, then the result will be cutting out a circle, which Iona wants.
But the girl's inquisitive mathematical mind does not rest: how many ways are there to cut a circle out of the canvas?
Input
The input contains two lines.
Each line has four space-separated integers xi, yi, ri, Ri, that describe the i-th ring; xi and yi are coordinates of the ring's center, ri and Ri are the internal and external radii of the ring correspondingly ( - 100 β€ xi, yi β€ 100; 1 β€ ri < Ri β€ 100).
It is guaranteed that the centers of the rings do not coinside.
Output
A single integer β the number of ways to cut out a circle from the canvas.
Examples
Input
60 60 45 55
80 80 8 32
Output
1
Input
60 60 45 55
80 60 15 25
Output
4
Input
50 50 35 45
90 50 35 45
Output
0
Note
Figures for test samples are given below. The possible cuts are marked with red dotted line.
<image> <image> <image>
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.
Fennec and Snuke are playing a board game.
On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree.
Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored.
Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell.
More specifically, each player performs the following action in her/his turn:
- Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black.
- Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white.
A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally.
-----Constraints-----
- 2 \leq N \leq 10^5
- 1 \leq a_i, b_i \leq N
- The given graph is a tree.
-----Input-----
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
-----Output-----
If Fennec wins, print Fennec; if Snuke wins, print Snuke.
-----Sample Input-----
7
3 6
1 2
3 1
7 4
5 7
1 4
-----Sample Output-----
Fennec
For example, if Fennec first paints Cell 2 black, she will win regardless of Snuke's moves.
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 following equation:
<image> where sign [a] represents the integer part of number a.
Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds.
Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn.
Input
The first line contains a single integer n (1 β€ n β€ 40).
Output
Print a single integer β the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists.
Examples
Input
1
Output
1
Input
2
Output
3
Input
3
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.
Problem statement
There is a rational number sequence $ X_0, X_1, X_2, ..., X_N $. Each term is defined as follows.
1. $ X_0 = 0 $
2. $ X_i = X_ {i-1} $ $ op_i $ $ Y_i $ ($ 1 \ leq i \ leq N $). However, $ op_i $ is $ + $, $ β $, $ Γ $, $ Γ· $ Either.
Find $ X_N $.
Constraint
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq o_i \ leq 4 $
* $ -10 ^ 6 \ leq Y_i \ leq 10 ^ 6 $
* If $ o_i = 4 $, then $ Y_i \ neq 0 $
* $ X_N $ is an integer greater than or equal to $ -2 ^ {31} $ and less than $ 2 ^ {31} $.
input
Input follows the following format. All given numbers are integers.
$ N $
$ o_1 $ $ Y_1 $
$ o_2 $ $ Y_2 $
$ ... $
$ o_N $ $ Y_N $
When $ o_i = 1 $, $ op_i $ is +, when $ o_i = 2 $, $ op_i $ is β, when $ o_i = 3 $, $ op_i $ is Γ, and when $ o_i = 4 $, $ op_i $ is Γ·.
output
Print the value of $ X_N $ on one line.
Example
Input
4
1 1
4 2
2 4
3 4
Output
-14
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.
Marcin is a coach in his university. There are $n$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.
Let's focus on the students. They are indexed with integers from $1$ to $n$. Each of them can be described with two integers $a_i$ and $b_i$; $b_i$ is equal to the skill level of the $i$-th student (the higher, the better). Also, there are $60$ known algorithms, which are numbered with integers from $0$ to $59$. If the $i$-th student knows the $j$-th algorithm, then the $j$-th bit ($2^j$) is set in the binary representation of $a_i$. Otherwise, this bit is not set.
Student $x$ thinks that he is better than student $y$ if and only if $x$ knows some algorithm which $y$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.
Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
-----Input-----
The first line contains one integer $n$ ($1 \leq n \leq 7000$) β the number of students interested in the camp.
The second line contains $n$ integers. The $i$-th of them is $a_i$ ($0 \leq a_i < 2^{60}$).
The third line contains $n$ integers. The $i$-th of them is $b_i$ ($1 \leq b_i \leq 10^9$).
-----Output-----
Output one integer which denotes the maximum sum of $b_i$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
-----Examples-----
Input
4
3 2 3 6
2 8 5 10
Output
15
Input
3
1 2 3
1 2 3
Output
0
Input
1
0
1
Output
0
-----Note-----
In the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $b_i$.
In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
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 upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored AΒ·BΒ·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.
At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) Γ (B - 2) Γ (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 Γ 1 Γ 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B ΠΈ C.
Given number n, find the minimally possible and maximally possible number of stolen hay blocks.
Input
The only line contains integer n from the problem's statement (1 β€ n β€ 109).
Output
Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
4
Output
28 41
Input
7
Output
47 65
Input
12
Output
48 105
Note
Let's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 Γ 4 Γ 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) Γ (4 - 2) Γ (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 Γ 3 Γ 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) Γ (3 - 2) Γ (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks.
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, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $n$ elements. The $i$-th element is $a_i$ ($i$ = $1, 2, \ldots, n$). He gradually takes the first two leftmost elements from the deque (let's call them $A$ and $B$, respectively), and then does the following: if $A > B$, he writes $A$ to the beginning and writes $B$ to the end of the deque, otherwise, he writes to the beginning $B$, and $A$ writes to the end of the deque. We call this sequence of actions an operation.
For example, if deque was $[2, 3, 4, 5, 1]$, on the operation he will write $B=3$ to the beginning and $A=2$ to the end, so he will get $[3, 4, 5, 1, 2]$.
The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $q$ queries. Each query consists of the singular number $m_j$ $(j = 1, 2, \ldots, q)$. It is required for each query to answer which two elements he will pull out on the $m_j$-th operation.
Note that the queries are independent and for each query the numbers $A$ and $B$ should be printed in the order in which they will be pulled out of the deque.
Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.
-----Input-----
The first line contains two integers $n$ and $q$ ($2 \leq n \leq 10^5$, $0 \leq q \leq 3 \cdot 10^5$)Β β the number of elements in the deque and the number of queries. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$, where $a_i$ $(0 \leq a_i \leq 10^9)$Β β the deque element in $i$-th position. The next $q$ lines contain one number each, meaning $m_j$ ($1 \leq m_j \leq 10^{18}$).
-----Output-----
For each teacher's query, output two numbers $A$ and $B$Β β the numbers that Valeriy pulls out of the deque for the $m_j$-th operation.
-----Examples-----
Input
5 3
1 2 3 4 5
1
2
10
Output
1 2
2 3
5 2
Input
2 0
0 0
Output
-----Note----- Consider all 10 steps for the first test in detail: $[1, 2, 3, 4, 5]$Β β on the first operation, $A$ and $B$ are $1$ and $2$, respectively.
So, $2$ we write to the beginning of the deque, and $1$Β β to the end.
We get the following status of the deque: $[2, 3, 4, 5, 1]$. $[2, 3, 4, 5, 1] \Rightarrow A = 2, B = 3$. $[3, 4, 5, 1, 2]$ $[4, 5, 1, 2, 3]$ $[5, 1, 2, 3, 4]$ $[5, 2, 3, 4, 1]$ $[5, 3, 4, 1, 2]$ $[5, 4, 1, 2, 3]$ $[5, 1, 2, 3, 4]$ $[5, 2, 3, 4, 1] \Rightarrow A = 5, B = 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.
Write a function which takes a number and returns the corresponding ASCII char for that value.
Example:
~~~if-not:java,racket
```
get_char(65) # => 'A'
```
~~~
~~~if:java
~~~
~~~if:racket
~~~
For ASCII table, you can refer to http://www.asciitable.com/
Write your solution by modifying this code:
```python
def get_char(c):
```
Your solution should implemented in the function "get_char". 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 an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!
You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose:
* The x\% of the price of each the a-th sold ticket (a-th, 2a-th, 3a-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources.
* The y\% of the price of each the b-th sold ticket (b-th, 2b-th, 3b-th and so on) in the order you chose is aimed for pollution abatement.
If the ticket is in both programs then the (x + y) \% are used for environmental activities. Also, it's known that all prices are multiples of 100, so there is no need in any rounding.
For example, if you'd like to sell tickets with prices [400, 100, 300, 200] and the cinema pays 10\% of each 2-nd sold ticket and 20\% of each 3-rd sold ticket, then arranging them in order [100, 200, 300, 400] will lead to contribution equal to 100 β
0 + 200 β
0.1 + 300 β
0.2 + 400 β
0.1 = 120. But arranging them in order [100, 300, 400, 200] will lead to 100 β
0 + 300 β
0.1 + 400 β
0.2 + 200 β
0.1 = 130.
Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least k in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least k.
Input
The first line contains a single integer q (1 β€ q β€ 100) β the number of independent queries. Each query consists of 5 lines.
The first line of each query contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of tickets.
The second line contains n integers p_1, p_2, ..., p_n (100 β€ p_i β€ 10^9, p_i mod 100 = 0) β the corresponding prices of tickets.
The third line contains two integers x and a (1 β€ x β€ 100, x + y β€ 100, 1 β€ a β€ n) β the parameters of the first program.
The fourth line contains two integers y and b (1 β€ y β€ 100, x + y β€ 100, 1 β€ b β€ n) β the parameters of the second program.
The fifth line contains single integer k (1 β€ k β€ 10^{14}) β the required total contribution.
It's guaranteed that the total number of tickets per test doesn't exceed 2 β
10^5.
Output
Print q integers β one per query.
For each query, print the minimum number of tickets you need to sell to make the total ecological contribution of at least k if you can sell tickets in any order.
If the total contribution can not be achieved selling all the tickets, print -1.
Example
Input
4
1
100
50 1
49 1
100
8
100 200 100 200 100 200 100 100
10 2
15 3
107
3
1000000000 1000000000 1000000000
50 1
50 1
3000000000
5
200 100 100 100 100
69 5
31 2
90
Output
-1
6
3
4
Note
In the first query the total contribution is equal to 50 + 49 = 99 < 100, so it's impossible to gather enough money.
In the second query you can rearrange tickets in a following way: [100, 100, 200, 200, 100, 200, 100, 100] and the total contribution from the first 6 tickets is equal to 100 β
0 + 100 β
0.1 + 200 β
0.15 + 200 β
0.1 + 100 β
0 + 200 β
0.25 = 10 + 30 + 20 + 50 = 110.
In the third query the full price of each ticket goes to the environmental activities.
In the fourth query you can rearrange tickets as [100, 200, 100, 100, 100] and the total contribution from the first 4 tickets is 100 β
0 + 200 β
0.31 + 100 β
0 + 100 β
0.31 = 62 + 31 = 93.
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've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.
You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly $x$ days and that's the exact number of days you will spend visiting your friend. You will spend exactly $x$ consecutive (successive) days visiting Coronavirus-chan.
They use a very unusual calendar in Naha: there are $n$ months in a year, $i$-th month lasts exactly $d_i$ days. Days in the $i$-th month are numbered from $1$ to $d_i$. There are no leap years in Naha.
The mood of Coronavirus-chan (and, accordingly, her desire to hug you) depends on the number of the day in a month. In particular, you get $j$ hugs if you visit Coronavirus-chan on the $j$-th day of the month.
You know about this feature of your friend and want to plan your trip to get as many hugs as possible (and then maybe you can win the heart of Coronavirus-chan).
Please note that your trip should not necessarily begin and end in the same year.
-----Input-----
The first line of input contains two integers $n$ and $x$ ($1 \le n \le 2 \cdot 10^5$) β the number of months in the year and the number of days you can spend with your friend.
The second line contains $n$ integers $d_1, d_2, \ldots, d_n$, $d_i$ is the number of days in the $i$-th month ($1 \le d_i \le 10^6$).
It is guaranteed that $1 \le x \le d_1 + d_2 + \ldots + d_n$.
-----Output-----
Print one integer β the maximum number of hugs that you can get from Coronavirus-chan during the best vacation in your life.
-----Examples-----
Input
3 2
1 3 1
Output
5
Input
3 6
3 3 3
Output
12
Input
5 6
4 2 3 1 3
Output
15
-----Note-----
In the first test case, the numbers of the days in a year are (indices of days in a corresponding month) $\{1,1,2,3,1\}$. Coronavirus-chan will hug you the most if you come on the third day of the year: $2+3=5$ hugs.
In the second test case, the numbers of the days are $\{1,2,3,1,2,3,1,2,3\}$. You will get the most hugs if you arrive on the third day of the year: $3+1+2+3+1+2=12$ hugs.
In the third test case, the numbers of the days are $\{1,2,3,4,1,2, 1,2,3, 1, 1,2,3\}$. You will get the most hugs if you come on the twelfth day of the year: your friend will hug you $2+3+1+2+3+4=15$ times.
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.
Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.
This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.
-----Input-----
The first line contains two integers n and m (1 β€ n β€ 100;Β 0 β€ m β€ 10^4). The next m lines contain the debts. The i-th line contains three integers a_{i}, b_{i}, c_{i} (1 β€ a_{i}, b_{i} β€ n;Β a_{i} β b_{i};Β 1 β€ c_{i} β€ 100), which mean that person a_{i} owes person b_{i} c_{i} rubles.
Assume that the people are numbered by integers from 1 to n.
It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).
-----Output-----
Print a single integer β the minimum sum of debts in the optimal rearrangement.
-----Examples-----
Input
5 3
1 2 10
2 3 1
2 4 1
Output
10
Input
3 0
Output
0
Input
4 3
1 2 1
2 3 1
3 1 1
Output
0
-----Note-----
In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.
In the second sample, there are no debts.
In the third sample, you can annul all the debts.
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 Snuke Cats numbered 1, 2, \ldots, N, where N is even.
Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.
Recently, they learned the operation called xor (exclusive OR).What is xor?
For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows:
- When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.
For example, 3~\textrm{xor}~5 = 6.
They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf.
We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i.
Using this information, restore the integer written on the scarf of each Snuke Cat.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 200000
- N is even.
- 0 \leq a_i \leq 10^9
- There exists a combination of integers on the scarfs that is consistent with the given information.
-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N
-----Output-----
Print a line containing N integers separated with space.
The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i.
If there are multiple possible solutions, you may print any of them.
-----Sample Input-----
4
20 11 9 24
-----Sample Output-----
26 5 7 22
- 5~\textrm{xor}~7~\textrm{xor}~22 = 20
- 26~\textrm{xor}~7~\textrm{xor}~22 = 11
- 26~\textrm{xor}~5~\textrm{xor}~22 = 9
- 26~\textrm{xor}~5~\textrm{xor}~7 = 24
Thus, this output is consistent with the given information.
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.
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array.
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.
Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.
You are given two matrices $A$ and $B$ of size $n \times m$, each of which consists of $0$ and $1$ only. You can apply the following operation to the matrix $A$ arbitrary number of times: take any submatrix of the matrix $A$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $0$, will be replaced by $1$, and all corners of the submatrix that contain $1$, will be replaced by $0$). You have to answer whether you can obtain the matrix $B$ from the matrix $A$. [Image] An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow.
Ramesses don't want to perform these operations by himself, so he asks you to answer this question.
A submatrix of matrix $M$ is a matrix which consist of all elements which come from one of the rows with indices $x_1, x_1+1, \ldots, x_2$ of matrix $M$ and one of the columns with indices $y_1, y_1+1, \ldots, y_2$ of matrix $M$, where $x_1, x_2, y_1, y_2$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$, where the cell $(i,j)$ denotes the cell on the intersection of the $i$-th row and the $j$-th column.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 500$)Β β the number of rows and the number of columns in matrices $A$ and $B$.
Each of the next $n$ lines contain $m$ integers: the $j$-th integer in the $i$-th line is the $j$-th element of the $i$-th row of the matrix $A$ ($0 \leq A_{ij} \leq 1$).
Each of the next $n$ lines contain $m$ integers: the $j$-th integer in the $i$-th line is the $j$-th element of the $i$-th row of the matrix $B$ ($0 \leq B_{ij} \leq 1$).
-----Output-----
Print "Yes" (without quotes) if it is possible to transform the matrix $A$ to the matrix $B$ using the operations described above, and "No" (without quotes), if it is not possible. You can print each letter in any case (upper or lower).
-----Examples-----
Input
3 3
0 1 0
0 1 0
1 0 0
1 0 0
1 0 0
1 0 0
Output
Yes
Input
6 7
0 0 1 1 0 0 1
0 1 0 0 1 0 1
0 0 0 1 0 0 1
1 0 1 0 1 0 0
0 1 0 0 1 0 1
0 1 0 1 0 0 1
1 1 0 1 0 1 1
0 1 1 0 1 0 0
1 1 0 1 0 0 1
1 0 1 0 0 1 0
0 1 1 0 1 0 0
0 1 1 1 1 0 1
Output
Yes
Input
3 4
0 1 0 1
1 0 1 0
0 1 0 1
1 1 1 1
1 1 1 1
1 1 1 1
Output
No
-----Note-----
The examples are explained below. [Image] Example 1. [Image] Example 2. [Image] Example 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.
New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v.
As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the r_{i}-th road is going to become w_{i}, which is shorter than its length before. Assume that the current year is year 1.
Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c_1, c_2, c_3 and make exactly one warehouse in each city. The k-th (1 β€ k β€ 3) Santa will take charge of the warehouse in city c_{k}.
It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c_1, c_2) + d(c_2, c_3) + d(c_3, c_1) dollars. Santas are too busy to find the best place, so they decided to choose c_1, c_2, c_3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.
However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.
-----Input-----
The first line contains an integer n (3 β€ n β€ 10^5) β the number of cities in Tree World.
Next n - 1 lines describe the roads. The i-th line of them (1 β€ i β€ n - 1) contains three space-separated integers a_{i}, b_{i}, l_{i} (1 β€ a_{i}, b_{i} β€ n, a_{i} β b_{i}, 1 β€ l_{i} β€ 10^3), denoting that the i-th road connects cities a_{i} and b_{i}, and the length of i-th road is l_{i}.
The next line contains an integer q (1 β€ q β€ 10^5) β the number of road length changes.
Next q lines describe the length changes. The j-th line of them (1 β€ j β€ q) contains two space-separated integers r_{j}, w_{j} (1 β€ r_{j} β€ n - 1, 1 β€ w_{j} β€ 10^3). It means that in the j-th repair, the length of the r_{j}-th road becomes w_{j}. It is guaranteed that w_{j} is smaller than the current length of the r_{j}-th road. The same road can be repaired several times.
-----Output-----
Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10^{ - 6}.
-----Examples-----
Input
3
2 3 5
1 3 3
5
1 4
2 2
1 2
2 1
1 1
Output
14.0000000000
12.0000000000
8.0000000000
6.0000000000
4.0000000000
Input
6
1 5 3
5 3 2
6 1 7
1 4 4
5 2 3
5
1 2
2 1
3 5
4 1
5 2
Output
19.6000000000
18.6000000000
16.6000000000
13.6000000000
12.6000000000
-----Note-----
Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 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.
On March 14, the day of the number $\pi$ is celebrated all over the world. This is a very important mathematical constant equal to the ratio of the circumference of a circle to its diameter.
Polycarp was told at school that the number $\pi$ is irrational, therefore it has an infinite number of digits in decimal notation. He wanted to prepare for the Day of the number $\pi$ by memorizing this number as accurately as possible.
Polycarp wrote out all the digits that he managed to remember. For example, if Polycarp remembered $\pi$ as $3.1415$, he wrote out 31415.
Polycarp was in a hurry and could have made a mistake, so you decided to check how many first digits of the number $\pi$ Polycarp actually remembers correctly.
-----Input-----
The first line of the input data contains the single integer $t$ ($1 \le t \le 10^3$) β the number of test cases in the test.
Each test case is described by a single string of digits $n$, which was written out by Polycarp.
The string $n$ contains up to $30$ digits.
-----Output-----
Output $t$ integers, each of which is the answer to the corresponding test case, that is how many first digits of the number $\pi$ Polycarp remembers correctly.
-----Examples-----
Input
9
000
3
4141592653
141592653589793238462643383279
31420
31415
314159265358
27182
314159265358979323846264338327
Output
0
1
0
0
3
5
12
0
30
-----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.
Shubham has an array $a$ of size $n$, and wants to select exactly $x$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
-----Input-----
The first line of the input contains a single integer $t$ $(1\le t \le 100)$Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers $n$ and $x$ $(1 \le x \le n \le 1000)$Β β the length of the array and the number of elements you need to choose.
The next line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 1000)$Β β elements of the array.
-----Output-----
For each test case, print "Yes" or "No" depending on whether it is possible to choose $x$ elements such that their sum is odd.
You may print every letter in any case you want.
-----Example-----
Input
5
1 1
999
1 1
1000
2 1
51 50
2 2
51 50
3 3
101 102 103
Output
Yes
No
Yes
Yes
No
-----Note-----
For $1$st case: We must select element $999$, and the sum is odd.
For $2$nd case: We must select element $1000$, so overall sum is not odd.
For $3$rd case: We can select element $51$.
For $4$th case: We must select both elements $50$ and $51$ Β β so overall sum is odd.
For $5$th case: We must select all elements Β β but overall sum is not odd.
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 problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.
Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had pi points.
Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort ei he needs to invest to win against the i-th contestant. Losing a fight costs no effort.
After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here.
Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible.
Input
The first line contains a pair of integers n and k (1 β€ k β€ n + 1). The i-th of the following n lines contains two integers separated by a single space β pi and ei (0 β€ pi, ei β€ 200000).
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem C1 (4 points), the constraint 1 β€ n β€ 15 will hold.
* In subproblem C2 (4 points), the constraint 1 β€ n β€ 100 will hold.
* In subproblem C3 (8 points), the constraint 1 β€ n β€ 200000 will hold.
Output
Print a single number in a single line β the minimum amount of effort Manao needs to use to rank in the top k. If no amount of effort can earn Manao such a rank, output number -1.
Examples
Input
3 2
1 1
1 4
2 2
Output
3
Input
2 1
3 2
4 0
Output
-1
Input
5 2
2 10
2 10
1 1
3 1
3 1
Output
12
Note
Consider the first test case. At the time when Manao joins the tournament, there are three fighters. The first of them has 1 tournament point and the victory against him requires 1 unit of effort. The second contestant also has 1 tournament point, but Manao needs 4 units of effort to defeat him. The third contestant has 2 points and victory against him costs Manao 2 units of effort. Manao's goal is top be in top 2. The optimal decision is to win against fighters 1 and 3, after which Manao, fighter 2, and fighter 3 will all have 2 points. Manao will rank better than fighter 3 and worse than fighter 2, thus finishing in second place.
Consider the second test case. Even if Manao wins against both opponents, he will still rank third.
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.
With the motto "Creating your own path," a shrine created a fortune-telling fortune with its own hands. Ask the person who draws the lottery to throw six stones first, then the line segment connecting the first and second of the thrown stones, the line segment connecting the third and fourth, the fifth and six The fortune is determined from the area of ββthe triangle whose apex is the intersection of the three line segments connecting the second line segment. The relationship between each fortune and the area of ββthe triangle is as follows.
Area of ββa triangle whose apex is the intersection of line segments | Fortune
--- | ---
Over 1,900,000 | Daikichi
1,000,000 or more and less than 1,900,000 | Nakayoshi (chu-kichi)
100,000 or more and less than 1,000,000 | Kichi
Greater than 0 and less than 100,000 | Kokichi (syo-kichi)
No triangle | Kyo
However, the size of the area of ββthe triangle is determined by the priest by hand, so it cannot be said to be accurate and it takes time. So, as an excellent programmer living in the neighborhood, you decided to write a program as soon as possible to help the priest.
Create a program that takes the information of three line segments as input and outputs the fortune from the area of ββthe triangle whose vertices are the intersections of the line segments. The line segment information is given the coordinates of the start point (x1, y1) and the coordinates of the end point (x2, y2), and the coordinates of the start point and the end point must be different. Also, if two or more line segments are on the same straight line, if there are two line segments that do not have intersections, or if three line segments intersect at one point, it is "no triangle".
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by four zero lines. Each dataset is given in the following format:
line1
line2
line3
The i-th line is given the information of the i-th line segment. Information for each line is given in the following format.
x1 y1 x2 y2
Integers (x1, y1), (x2, y2) (-1000 β€ x1, y1, x2, y2 β€ 1000) representing the coordinates of the endpoints of the line segment are given, separated by blanks.
Output
The result of the fortune telling is output to one line for each data set.
Example
Input
-3 -2 9 6
3 -2 7 6
-1 0 5 0
2 2 -1 -1
0 1 2 1
-3 -1 3 1
0 0 0 0
Output
syo-kichi
kyo
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 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.
-----Constraints-----
- The length of S is 4.
- S consists of uppercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.
-----Sample Input-----
ASSA
-----Sample Output-----
Yes
S consists of A and S which both appear twice in S.
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.
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.
Now each knight ponders: how many coins he can have if only he kills other knights?
You should answer this question for each knight.
-----Input-----
The first line contains two integers $n$ and $k$ $(1 \le n \le 10^5, 0 \le k \le \min(n-1,10))$ β the number of knights and the number $k$ from the statement.
The second line contains $n$ integers $p_1, p_2 ,\ldots,p_n$ $(1 \le p_i \le 10^9)$ β powers of the knights. All $p_i$ are distinct.
The third line contains $n$ integers $c_1, c_2 ,\ldots,c_n$ $(0 \le c_i \le 10^9)$ β the number of coins each knight has.
-----Output-----
Print $n$ integers β the maximum number of coins each knight can have it only he kills other knights.
-----Examples-----
Input
4 2
4 5 9 7
1 2 11 33
Output
1 3 46 36
Input
5 1
1 2 3 4 5
1 2 3 4 5
Output
1 3 5 7 9
Input
1 0
2
3
Output
3
-----Note-----
Consider the first example. The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has. The second knight can kill the first knight and add his coin to his own two. The third knight is the strongest, but he can't kill more than $k = 2$ other knights. It is optimal to kill the second and the fourth knights: $2+11+33 = 46$. The fourth knight should kill the first and the second knights: $33+1+2 = 36$.
In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own.
In the third example there is only one knight, so he can't kill anyone.
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 tree T with N vertices, numbered 1 through N. For each 1 β€ i β€ N - 1, the i-th edge connects vertices a_i and b_i.
Snuke is constructing a directed graph T' by arbitrarily assigning direction to each edge in T. (There are 2^{N - 1} different ways to construct T'.)
For a fixed T', we will define d(s,\ t) for each 1 β€ s,\ t β€ N, as follows:
* d(s,\ t) = (The number of edges that must be traversed against the assigned direction when traveling from vertex s to vertex t)
In particular, d(s,\ s) = 0 for each 1 β€ s β€ N. Also note that, in general, d(s,\ t) β d(t,\ s).
We will further define D as the following:
3d2f3f88e8fa23f065c04cd175c14ebf.png
Snuke is constructing T' so that D will be the minimum possible value. How many different ways are there to construct T' so that D will be the minimum possible value, modulo 10^9 + 7?
Constraints
* 2 β€ N β€ 1000
* 1 β€ a_i,\ b_i β€ N
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
Print the number of the different ways to construct T' so that D will be the minimum possible value, modulo 10^9 + 7.
Examples
Input
4
1 2
1 3
1 4
Output
2
Input
4
1 2
2 3
3 4
Output
6
Input
6
1 2
1 3
1 4
2 5
2 6
Output
14
Input
10
2 4
2 5
8 3
10 7
1 6
2 8
9 5
8 6
10 6
Output
102
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 be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros.
For example, `solve("gh12cdy695m1") = 695`, because this is the largest of all number groupings.
Good luck!
Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
Write your solution by modifying this code:
```python
def solve(s):
```
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.
It's the most hotly anticipated game of the school year - Gryffindor vs Slytherin! Write a function which returns the winning team.
You will be given two arrays with two values.
The first given value is the number of points scored by the team's Chasers and the second a string with a 'yes' or 'no' value if the team caught the golden snitch!
The team who catches the snitch wins their team an extra 150 points - but doesn't always win them the game.
If the score is a tie return "It's a draw!""
** The game only ends when someone catches the golden snitch, so one array will always include 'yes' or 'no.' Points scored by Chasers can be any positive integer.
Write your solution by modifying this code:
```python
def game_winners(gryffindor, slytherin):
```
Your solution should implemented in the function "game_winners". 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.
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: <image>. Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xaΒ·ybΒ·zc.
To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 β€ x, y, z; x + y + z β€ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.
Note that in this problem, it is considered that 00 = 1.
Input
The first line contains a single integer S (1 β€ S β€ 103) β the maximum sum of coordinates of the sought point.
The second line contains three space-separated integers a, b, c (0 β€ a, b, c β€ 103) β the numbers that describe the metric of mushroom scientists.
Output
Print three real numbers β the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations.
A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) = - β.
Examples
Input
3
1 1 1
Output
1.0 1.0 1.0
Input
3
2 0 0
Output
3.0 0.0 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.
Rational numbers are numbers represented by ratios of two integers. For a prime number p, one of the elementary theorems in the number theory is that there is no rational number equal to βp. Such numbers are called irrational numbers. It is also known that there are rational numbers arbitrarily close to βp
Now, given a positive integer n, we define a set Qn of all rational numbers whose elements are represented by ratios of two positive integers both of which are less than or equal to n. For example, Q4 is a set of 11 rational numbers {1/1, 1/2, 1/3, 1/4, 2/1, 2/3, 3/1, 3/2, 3/4, 4/1, 4/3}. 2/2, 2/4, 3/3, 4/2 and 4/4 are not included here because they are equal to 1/1, 1/2, 1/1, 2/1 and 1/1, respectively.
Your job is to write a program that reads two integers p and n and reports two rational numbers x / y and u / v, where u / v < βp < x / y and there are no other elements of Qn between u/v and x/y. When n is greater than βp, such a pair of rational numbers always exists.
Input
The input consists of lines each of which contains two positive integers, a prime number p and an integer n in the following format.
p n
They are separated by a space character. You can assume that p and n are less than 10000, and that n is greater than βp. The end of the input is indicated by a line consisting of two zeros.
Output
For each input line, your program should output a line consisting of the two rational numbers x / y and u / v (x / y > u / v) separated by a space character in the following format.
x/y u/v
They should be irreducible. For example, 6/14 and 15/3 are not accepted. They should be reduced to 3/7 and 5/1, respectively.
Example
Input
2 5
3 10
5 100
0 0
Output
3/2 4/3
7/4 5/3
85/38 38/17
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 lighthouse keeper Peter commands an army of $n$ battle lemmings. He ordered his army to stand in a line and numbered the lemmings from $1$ to $n$ from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.
The more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.
Now it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders: give the shield to the left neighbor if it exists and doesn't have a shield; give the shield to the right neighbor if it exists and doesn't have a shield.
In one second Peter can give exactly one order.
It's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each $k$ from $0$ to $\frac{n(n-1)}2$, if he gives no more that $k$ orders. Help Peter to calculate it!
-----Input-----
First line contains a single integer $n$ ($1 \le n \le 80$), the number of lemmings in Peter's army.
Second line contains $n$ integers $a_i$ ($0 \le a_i \le 1$). If $a_i = 1$, then the $i$-th lemming has a shield, otherwise $a_i = 0$.
-----Output-----
Print $\frac{n(n-1)}2 + 1$ numbers, the greatest possible protection after no more than $0, 1, \dots, \frac{n(n-1)}2$ orders.
-----Examples-----
Input
5
1 0 0 0 1
Output
0 2 3 3 3 3 3 3 3 3 3
Input
12
0 0 0 0 1 1 1 1 0 1 1 0
Output
9 12 13 14 14 14 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15
-----Note-----
Consider the first example.
The protection is initially equal to zero, because for each pair of lemmings without shields there is no lemmings with shield.
In one second Peter can order the first lemming give his shield to the right neighbor. In this case, the protection is two, as there are two protected pairs of lemmings, $(1, 3)$ and $(1, 4)$.
In two seconds Peter can act in the following way. First, he orders the fifth lemming to give a shield to the left neighbor. Then, he orders the first lemming to give a shield to the right neighbor. In this case Peter has three protected pairs of lemmingsΒ β $(1, 3)$, $(1, 5)$ and $(3, 5)$.
You can make sure that it's impossible to give orders in such a way that the protection becomes greater than three.
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's new hobby is painting, but he learned the fact that it's not easy to paint 2D pictures in a hard way, after wasting a lot of canvas paper, paint and of course time. From now on, he decided to paint 1D pictures only.
Chef's canvas is N millimeters long and is initially all white. For simplicity, colors will be represented by an integer between 0 and 105. 0 indicates white. The picture he is envisioning is also N millimeters long and the ith millimeter consists purely of the color Ci. Unfortunately, his brush isn't fine enough to paint every millimeter one by one. The brush is 3 millimeters wide and so it can only paint three millimeters at a time with the same color. Painting over the same place completely replaces the color by the new one. Also, Chef has lots of bottles of paints of each color, so he will never run out of paint of any color.
Chef also doesn't want to ruin the edges of the canvas, so he doesn't want to paint any part beyond the painting. This means, for example, Chef cannot paint just the first millimeter of the canvas, or just the last two millimeters, etc.
Help Chef by telling him whether he can finish the painting or not with these restrictions.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N. The second line contains N space-separated integers C1, C2, ..., CN denoting the colors of Chef's painting.
-----Output-----
For each test case, output a single line containing either βYesβ or βNoβ (without quotes), denoting whether Chef can finish the painting or not.
-----Constraints-----
- 1 β€ T β€ 105
- 3 β€ N β€ 105
- The sum of the Ns over all the test cases in a single test file is β€ 5Γ105
- 1 β€ Ci β€ 105
-----Example-----
Input:3
4
1 5 5 5
4
1 1 1 5
3
5 5 2
Output:Yes
Yes
No
-----Explanation-----
Example case 1. Chef's canvas initially contains the colors [0,0,0,0]. Chef can finish the painting by first painting the first three millimeters with color 1, so the colors become [1,1,1,0], and then the last three millimeters with color 5 so that it becomes [1,5,5,5].
Example case 2. Chef's canvas initially contains the colors [0,0,0,0]. Chef can finish the painting by first painting the last three millimeters by color 5 so the colors become [0,5,5,5], and then the first three millimeters by color 1 so it becomes [1,1,1,5].
Example case 3. In this test case, Chef can only paint the painting as a whole, so all parts must have the same color, and the task is impossible.
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.
Mr. Takahashi has a string s consisting of lowercase English letters. He repeats the following operation on s exactly K times.
* Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of `z` is `a`.
For example, if you perform an operation for the second letter on `aaz`, `aaz` becomes `abz`. If you then perform an operation for the third letter on `abz`, `abz` becomes `aba`.
Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s. Find the such string.
Constraints
* 1β€|s|β€10^5
* All letters in s are lowercase English letters.
* 1β€Kβ€10^9
Input
The input is given from Standard Input in the following format:
s
K
Output
Print the lexicographically smallest string after performing exactly K operations on s.
Examples
Input
xyz
4
Output
aya
Input
a
25
Output
z
Input
codefestival
100
Output
aaaafeaaivap
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.
It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.
There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.
Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.
-----Constraints-----
- 1 β€ N β€ 100
- 0 β€ a_i β€ 1000
- a_i is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
-----Output-----
Print the minimum distance to be traveled.
-----Sample Input-----
4
2 3 7 9
-----Sample Output-----
7
The travel distance of 7 can be achieved by starting at coordinate 9 and traveling straight to coordinate 2.
It is not possible to do with a travel distance of less than 7, and thus 7 is the minimum distance to be traveled.
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.
Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much.
A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at volume v (1 β€ v β€ a_{i}; v is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the i-th note was played on the guitar and the piano must equal b_{i}. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the i-th note at volumes x_{i} and y_{i} (x_{i} + y_{i} = b_{i}) correspondingly, Sereja's joy rises by x_{i}Β·y_{i}.
Sereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song!
-----Input-----
The first line of the input contains integer n (1 β€ n β€ 10^5) β the number of notes in the song. The second line contains n integers a_{i} (1 β€ a_{i} β€ 10^6). The third line contains n integers b_{i} (1 β€ b_{i} β€ 10^6).
-----Output-----
In a single line print an integer β the maximum possible joy Sereja feels after he listens to a song.
-----Examples-----
Input
3
1 1 2
2 2 3
Output
4
Input
1
2
5
Output
-1
-----Note-----
In the first sample, Dima and Inna play the first two notes at volume 1 (1 + 1 = 2, the condition holds), they should play the last note at volumes 1 and 2. Sereja's total joy equals: 1Β·1 + 1Β·1 + 1Β·2 = 4.
In the second sample, there is no such pair (x, y), that 1 β€ x, y β€ 2, x + y = 5, so Dima and Inna skip a note. Sereja's total joy equals -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.
# Don't give me five!
In this kata you get the start number and the end number of a region and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive!
Examples:
```
1,9 -> 1,2,3,4,6,7,8,9 -> Result 8
4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> Result 12
```
The result may contain fives. ;-)
The start number will always be smaller than the end number. Both numbers can be also negative!
I'm very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have also created other katas. Take a look if you enjoyed this kata!
Write your solution by modifying this code:
```python
def dont_give_me_five(start,end):
```
Your solution should implemented in the function "dont_give_me_five". 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.
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward).
[Image]
Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.
-----Input-----
The first line of the input contains a single number n (1 β€ n β€ 26) β the number of colors of beads. The second line contains after n positive integers a_{i} Β β the quantity of beads of i-th color. It is guaranteed that the sum of a_{i} is at least 2 and does not exceed 100 000.
-----Output-----
In the first line print a single numberΒ β the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace.
Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.
-----Examples-----
Input
3
4 2 1
Output
1
abacaba
Input
1
4
Output
4
aaaa
Input
2
1 1
Output
0
ab
-----Note-----
In the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture.
In the second sample there is only one way to compose a necklace.
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.
Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.
Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the i-th of them in a standing state occupies a w_{i} pixels wide and a h_{i} pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a h_{i} pixels wide and a w_{i} pixels high rectangle.
The total photo will have size W Γ H, where W is the total width of all the people rectangles, and H is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than n / 2 of them can lie on the ground (it would be strange if more than n / 2 gentlemen lie on the ground together, isn't it?..)
Help them to achieve this goal.
-----Input-----
The first line contains integer n (1 β€ n β€ 1000) β the number of friends.
The next n lines have two integers w_{i}, h_{i} (1 β€ w_{i}, h_{i} β€ 1000) each, representing the size of the rectangle, corresponding to the i-th friend.
-----Output-----
Print a single integer equal to the minimum possible area of the photo containing all friends if no more than n / 2 of them can lie on the ground.
-----Examples-----
Input
3
10 1
20 2
30 3
Output
180
Input
3
3 1
2 2
4 3
Output
21
Input
1
5 10
Output
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.
International Car Production Company (ICPC), one of the largest automobile manufacturers in the world, is now developing a new vehicle called "Two-Wheel Buggy". As its name suggests, the vehicle has only two wheels. Quite simply, "Two-Wheel Buggy" is made up of two wheels (the left wheel and the right wheel) and a axle (a bar connecting two wheels). The figure below shows its basic structure.
<image>
Figure 7: The basic structure of the buggy
Before making a prototype of this new vehicle, the company decided to run a computer simula- tion. The details of the simulation is as follows.
In the simulation, the buggy will move on the x-y plane. Let D be the distance from the center of the axle to the wheels. At the beginning of the simulation, the center of the axle is at (0, 0), the left wheel is at (-D, 0), and the right wheel is at (D, 0). The radii of two wheels are 1.
<image>
Figure 8: The initial position of the buggy
The movement of the buggy in the simulation is controlled by a sequence of instructions. Each instruction consists of three numbers, Lspeed, Rspeed and time. Lspeed and Rspeed indicate the rotation speed of the left and right wheels, respectively, expressed in degree par second. time indicates how many seconds these two wheels keep their rotation speed. If a speed of a wheel is positive, it will rotate in the direction that causes the buggy to move forward. Conversely, if a speed is negative, it will rotate in the opposite direction. For example, if we set Lspeed as -360, the left wheel will rotate 360-degree in one second in the direction that makes the buggy move backward. We can set Lspeed and Rspeed differently, and this makes the buggy turn left or right. Note that we can also set one of them positive and the other negative (in this case, the buggy will spin around).
<image>
Figure 9: Examples
Your job is to write a program that calculates the final position of the buggy given a instruction sequence. For simplicity, you can can assume that wheels have no width, and that they would never slip.
Input
The input consists of several datasets. Each dataset is formatted as follows.
N D
Lspeed1 Rspeed1 time1
.
.
.
Lspeedi Rspeedi timei
.
.
.
LspeedN RspeedN timeN
The first line of a dataset contains two positive integers, N and D (1 β€ N β€ 100, 1 β€ D β€ 10). N indicates the number of instructions in the dataset, and D indicates the distance between the center of axle and the wheels. The following N lines describe the instruction sequence. The i-th line contains three integers, Lspeedi, i, and timei (-360 β€ Lspeedi, Rspeedi β€ 360, 1 β€ timei ), describing the i-th instruction to the buggy. You can assume that the sum of timei is at most 500.
The end of input is indicated by a line containing two zeros. This line is not part of any dataset and hence should not be processed.
Output
For each dataset, output two lines indicating the final position of the center of the axle. The first line should contain the x-coordinate, and the second line should contain the y-coordinate. The absolute error should be less than or equal to 10-3 . No extra character should appear in the output.
Example
Input
1 1
180 90 2
1 1
180 180 20
2 10
360 -360 5
-90 360 8
3 2
100 60 9
-72 -72 10
-45 -225 5
0 0
Output
3.00000
3.00000
0.00000
62.83185
12.00000
0.00000
-2.44505
13.12132
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.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour s_{i}, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c β Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer m_{i} and a lowercase letter c_{i}, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
-----Input-----
The first line of input contains a positive integer n (1 β€ n β€ 1 500) β the length of the garland.
The second line contains n lowercase English letters s_1s_2... s_{n} as a string β the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 β€ q β€ 200 000) β the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer m_{i} (1 β€ m_{i} β€ n) β the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter c_{i} β Koyomi's possible favourite colour.
-----Output-----
Output q lines: for each work plan, output one line containing an integer β the largest Koyomity achievable after repainting the garland according to it.
-----Examples-----
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
-----Note-----
In the first sample, there are three plans: In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable; In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6; In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 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.
The Dogeforces company has $k$ employees. Each employee, except for lower-level employees, has at least $2$ subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates.
The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 500$) β the number of lower-level employees.
This is followed by $n$ lines, where $i$-th line contains $n$ integers $a_{i,1}, a_{i,2}, \dots, a_{i,n}$ ($1 \le a_{i,j} \le 5000$) β salary of the common supervisor of employees with numbers $i$ and $j$. It is guaranteed that $a_{i,j} = a_{j,i}$. Note that $a_{i,i}$ is equal to the salary of the $i$-th employee.
-----Output-----
In the first line, print a single integer $k$ β the number of employees in the company.
In the second line, print $k$ integers $c_1, c_2, \dots, c_k$, where $c_i$ is the salary of the employee with the number $i$.
In the third line, print a single integer $r$ β the number of the employee who is the head of the company.
In the following $k-1$ lines, print two integers $v$ and $u$ ($1 \le v, u \le k$) β the number of the employee and his direct supervisor.
Note that the lower-level employees have numbers from $1$ to $n$, and for the rest of the employees, you have to assign numbers from $n+1$ to $k$. If there are several correct company structures, you can print any of them.
-----Examples-----
Input
3
2 5 7
5 1 7
7 7 4
Output
5
2 1 4 7 5
4
1 5
2 5
5 4
3 4
-----Note-----
One of the possible structures in the first example:
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 we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter.
[Image]
Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i.Β e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.
Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?
You have to determine the winner of the game for all initial positions of the marbles.
-----Input-----
The first line of input contains two integers n and m (2 β€ n β€ 100, $1 \leq m \leq \frac{n(n - 1)}{2}$).
The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 β€ v, u β€ n, v β u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.
-----Output-----
Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.
-----Examples-----
Input
4 4
1 2 b
1 3 a
2 4 c
3 4 b
Output
BAAA
ABAA
BBBA
BBBB
Input
5 8
5 3 h
1 2 c
3 1 c
3 2 r
5 1 r
4 3 z
5 4 r
5 2 h
Output
BABBB
BBBBB
AABBB
AAABA
AAAAB
-----Note-----
Here's the graph in the first sample test case:
[Image]
Here's the graph in the second sample test case:
[Image]
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.
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.
He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space):
### ..# .#. #..
.#. ### .#. ###
.#. ..# ### #..
Simon faced a quite natural challenge: placing in the given n Γ m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.
Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?
Input
The only line contains two space-separated integers n and m β the sizes of the warehouse (1 β€ n, m β€ 9).
Output
In the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use "." (dot) to mark empty space and use successive capital Latin letters ("A" for the first turboplow, "B" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.
Examples
Input
3 3
Output
1
AAA
.A.
.A.
Input
5 6
Output
4
A..C..
AAAC..
ABCCCD
.B.DDD
BBB..D
Input
2 2
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.
Take 2 strings `s1` and `s2` including only letters from `a`to `z`.
Return a new **sorted** string, the longest possible, containing distinct letters,
- each taken only once - coming from s1 or s2.
# Examples:
```
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"
```
Write your solution by modifying this code:
```python
def longest(s1, s2):
```
Your solution should implemented in the function "longest". 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.
Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.
From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k β₯ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k - 1 into one box of side length 2k, or as in the following figure:
<image>
Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.
Input
The first line of input contains an integer n (1 β€ n β€ 105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0 β€ ki β€ 109, 1 β€ ai β€ 109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct.
Output
Output a single integer p, such that the smallest magical box that can contain all of Emuskaldβs boxes has side length 2p.
Examples
Input
2
0 3
1 5
Output
3
Input
1
0 4
Output
1
Input
2
1 10
2 2
Output
3
Note
Picture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.
In the second test case, we can put all four small boxes into a box with side length 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.
Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.
To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a_1, a_2, ..., a_{k}.
Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n - k cities, and, of course, flour delivery should be paidΒ β for every kilometer of path between storage and bakery Masha should pay 1 ruble.
Formally, Masha will pay x roubles, if she will open the bakery in some city b (a_{i} β b for every 1 β€ i β€ k) and choose a storage in some city s (s = a_{j} for some 1 β€ j β€ k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).
Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.
-----Input-----
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 10^5, 0 β€ k β€ n)Β β the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively.
Then m lines follow. Each of them contains three integers u, v and l (1 β€ u, v β€ n, 1 β€ l β€ 10^9, u β v) meaning that there is a road between cities u and v of length of l kilometers .
If k > 0, then the last line of the input contains k distinct integers a_1, a_2, ..., a_{k} (1 β€ a_{i} β€ n)Β β the number of cities having flour storage located in. If k = 0 then this line is not presented in the input.
-----Output-----
Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line.
If the bakery can not be opened (while satisfying conditions) in any of the n cities, print - 1 in the only line.
-----Examples-----
Input
5 4 2
1 2 5
1 2 3
2 3 4
1 4 10
1 5
Output
3
Input
3 1 1
1 2 3
3
Output
-1
-----Note-----
[Image]
Image illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.
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 given a function that should insert an asterisk (`*`) between every pair of **even digits** in the given input, and return it as a string. If the input is a sequence, concat the elements first as a string.
## Input
The input can be an integer, a string of digits or a sequence containing integers only.
## Output
Return a string.
## Examples
```
5312708 --> "531270*8"
"0000" --> "0*0*0*0"
[1, 4, 64] --> "14*6*4"
```
Have fun!
Write your solution by modifying this code:
```python
def asterisc_it(n):
```
Your solution should implemented in the function "asterisc_it". 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.
Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits.
Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that i < j and the pair of integers a_{i} and a_{j} is k-interesting. Your task is to help Vasya and determine this number.
-----Input-----
The first line contains two integers n and k (2 β€ n β€ 10^5, 0 β€ k β€ 14) β the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ.
The second line contains the sequence a_1, a_2, ..., a_{n} (0 β€ a_{i} β€ 10^4), which Vasya has.
-----Output-----
Print the number of pairs (i, j) so that i < j and the pair of integers a_{i} and a_{j} is k-interesting.
-----Examples-----
Input
4 1
0 3 2 1
Output
4
Input
6 0
200 100 100 100 200 200
Output
6
-----Note-----
In the first test there are 4 k-interesting pairs: (1, 3), (1, 4), (2, 3), (2, 4).
In the second test k = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs: (1, 5), (1, 6), (2, 3), (2, 4), (3, 4), (5, 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.
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.
There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city v_{i} to city u_{i} (and from u_{i} to v_{i}), and it costs w_{i} coins to use this route.
Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is a_{i} coins.
You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j β i).
Formally, for every $i \in [ 1, n ]$ you have to calculate $\operatorname{min}_{j = 1} 2 d(i, j) + a_{j}$, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
-----Input-----
The first line contains two integers n and m (2 β€ n β€ 2Β·10^5, 1 β€ m β€ 2Β·10^5).
Then m lines follow, i-th contains three integers v_{i}, u_{i} and w_{i} (1 β€ v_{i}, u_{i} β€ n, v_{i} β u_{i}, 1 β€ w_{i} β€ 10^12) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input.
The next line contains n integers a_1, a_2, ... a_{k} (1 β€ a_{i} β€ 10^12) β price to attend the concert in i-th city.
-----Output-----
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j β i).
-----Examples-----
Input
4 2
1 2 4
2 3 7
6 20 1 25
Output
6 14 1 25
Input
3 3
1 2 1
2 3 1
1 3 1
30 10 20
Output
12 10 12
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 battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j.
Tayuya wants to play a melody of n notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference.
For example, if a = [1, 1, 2, 2, 3, 3], and the sequence of notes is 4, 11, 11, 12, 12, 13, 13 (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7, as shown on the picture.
<image>
Input
The first line contains 6 space-separated numbers a_{1}, a_{2}, ..., a_{6} (1 β€ a_{i} β€ 10^{9}) which describe the Tayuya's strings.
The second line contains the only integer n (1 β€ n β€ 100 000) standing for the number of notes in the melody.
The third line consists of n integers b_{1}, b_{2}, ..., b_{n} (1 β€ b_{i} β€ 10^{9}), separated by space. They describe the notes to be played. It's guaranteed that b_i > a_j for all 1β€ iβ€ n and 1β€ jβ€ 6, in other words, you can play each note on any string.
Output
Print the minimal possible difference of the maximal and the minimal indices of used frets.
Examples
Input
1 4 100 10 30 5
6
101 104 105 110 130 200
Output
0
Input
1 1 2 2 3 3
7
13 4 11 12 11 13 12
Output
7
Note
In the first sample test it is optimal to play the first note on the first string, the second note on the second string, the third note on the sixth string, the fourth note on the fourth string, the fifth note on the fifth string, and the sixth note on the third string. In this case the 100-th fret is used each time, so the difference is 100 - 100 = 0.
<image>
In the second test it's optimal, for example, to play the second note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7.
<image>
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 employees working in company "X" (let's number them from 1 to n for convenience). Initially the employees didn't have any relationships among each other. On each of m next days one of the following events took place: either employee y became the boss of employee x (at that, employee x didn't have a boss before); or employee x gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive); or comes a request of type "determine whether employee x signs certain documents".
Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies.
-----Input-----
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the number of employees and the number of events.
Each of the next m lines contains the description of one event (the events are given in the chronological order). The first number of the line determines the type of event t (1 β€ t β€ 3). If t = 1, then next follow two integers x and y (1 β€ x, y β€ n) β numbers of the company employees. It is guaranteed that employee x doesn't have the boss currently. If t = 2, then next follow integer x (1 β€ x β€ n) β the number of the employee who got a document packet. If t = 3, then next follow two integers x and i (1 β€ x β€ n;Β 1 β€ i β€ [number of packets that have already been given]) β the employee and the number of the document packet for which you need to find out information. The document packets are numbered started from 1 in the chronological order.
It is guaranteed that the input has at least one query of the third type.
-----Output-----
For each query of the third type print "YES" if the employee signed the document package and "NO" otherwise. Print all the words without the quotes.
-----Examples-----
Input
4 9
1 4 3
2 4
3 3 1
1 2 3
2 2
3 1 2
1 3 1
2 2
3 1 3
Output
YES
NO
YES
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 four integers $n$, $B$, $x$ and $y$. You should build a sequence $a_0, a_1, a_2, \dots, a_n$ where $a_0 = 0$ and for each $i \ge 1$ you can choose:
either $a_i = a_{i - 1} + x$
or $a_i = a_{i - 1} - y$.
Your goal is to build such a sequence $a$ that $a_i \le B$ for all $i$ and $\sum\limits_{i=0}^{n}{a_i}$ is maximum possible.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) β the number of test cases. Next $t$ cases follow.
The first and only line of each test case contains four integers $n$, $B$, $x$ and $y$ ($1 \le n \le 2 \cdot 10^5$; $1 \le B, x, y \le 10^9$).
It's guaranteed that the total sum of $n$ doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case, print one integer β the maximum possible $\sum\limits_{i=0}^{n}{a_i}$.
-----Examples-----
Input
3
5 100 1 30
7 1000000000 1000000000 1000000000
4 1 7 3
Output
15
4000000000
-10
-----Note-----
In the first test case, the optimal sequence $a$ is $[0, 1, 2, 3, 4, 5]$.
In the second test case, the optimal sequence $a$ is $[0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9]$.
In the third test case, the optimal sequence $a$ is $[0, -3, -6, 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.
ΠΠ°ΠΌΡΡΡ ΠΊΠΎΠΌΠΏΡΡΡΠ΅ΡΠ° ΡΠΎΡΡΠΎΠΈΡ ΠΈΠ· n ΡΡΠ΅Π΅ΠΊ, ΠΊΠΎΡΠΎΡΡΠ΅ Π²ΡΡΡΡΠΎΠ΅Π½Ρ Π² ΡΡΠ΄. ΠΡΠΎΠ½ΡΠΌΠ΅ΡΡΠ΅ΠΌ ΡΡΠ΅ΠΉΠΊΠΈ ΠΎΡ 1 Π΄ΠΎ n ΡΠ»Π΅Π²Π° Π½Π°ΠΏΡΠ°Π²ΠΎ. ΠΡΠΎ ΠΊΠ°ΠΆΠ΄ΡΡ ΡΡΠ΅ΠΉΠΊΡ ΠΈΠ·Π²Π΅ΡΡΠ½ΠΎ, ΡΠ²ΠΎΠ±ΠΎΠ΄Π½Π° ΠΎΠ½Π° ΠΈΠ»ΠΈ ΠΏΡΠΈΠ½Π°Π΄Π»Π΅ΠΆΠΈΡ ΠΊΠ°ΠΊΠΎΠΌΡ-Π»ΠΈΠ±ΠΎ ΠΏΡΠΎΡΠ΅ΡΡΡ (Π² ΡΠ°ΠΊΠΎΠΌ ΡΠ»ΡΡΠ°Π΅ ΠΈΠ·Π²Π΅ΡΡΠ΅Π½ ΠΏΡΠΎΡΠ΅ΡΡ, ΠΊΠΎΡΠΎΡΠΎΠΌΡ ΠΎΠ½Π° ΠΏΡΠΈΠ½Π°Π΄Π»Π΅ΠΆΠΈΡ).
ΠΠ»Ρ ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ ΠΏΡΠΎΡΠ΅ΡΡΠ° ΠΈΠ·Π²Π΅ΡΡΠ½ΠΎ, ΡΡΠΎ ΠΏΡΠΈΠ½Π°Π΄Π»Π΅ΠΆΠ°ΡΠΈΠ΅ Π΅ΠΌΡ ΡΡΠ΅ΠΉΠΊΠΈ Π·Π°Π½ΠΈΠΌΠ°ΡΡ Π² ΠΏΠ°ΠΌΡΡΠΈ Π½Π΅ΠΏΡΠ΅ΡΡΠ²Π½ΡΠΉ ΡΡΠ°ΡΡΠΎΠΊ. Π‘ ΠΏΠΎΠΌΠΎΡΡΡ ΠΎΠΏΠ΅ΡΠ°ΡΠΈΠΉ Π²ΠΈΠ΄Π° Β«ΠΏΠ΅ΡΠ΅ΠΏΠΈΡΠ°ΡΡ Π΄Π°Π½Π½ΡΠ΅ ΠΈΠ· Π·Π°Π½ΡΡΠΎΠΉ ΡΡΠ΅ΠΉΠΊΠΈ Π² ΡΠ²ΠΎΠ±ΠΎΠ΄Π½ΡΡ, Π° Π·Π°Π½ΡΡΡΡ ΡΠ΅ΠΏΠ΅ΡΡ ΡΡΠΈΡΠ°ΡΡ ΡΠ²ΠΎΠ±ΠΎΠ΄Π½ΠΎΠΉΒ» ΡΡΠ΅Π±ΡΠ΅ΡΡΡ ΡΠ°ΡΠΏΠΎΠ»ΠΎΠΆΠΈΡΡ Π²ΡΠ΅ ΠΏΡΠΈΠ½Π°Π΄Π»Π΅ΠΆΠ°ΡΠΈΠ΅ ΠΏΡΠΎΡΠ΅ΡΡΠ°ΠΌ ΡΡΠ΅ΠΉΠΊΠΈ Π² Π½Π°ΡΠ°Π»Π΅ ΠΏΠ°ΠΌΡΡΠΈ ΠΊΠΎΠΌΠΏΡΡΡΠ΅ΡΠ°. ΠΡΡΠ³ΠΈΠΌΠΈ ΡΠ»ΠΎΠ²Π°ΠΌΠΈ, Π»ΡΠ±Π°Ρ ΡΠ²ΠΎΠ±ΠΎΠ΄Π½Π°Ρ ΡΡΠ΅ΠΉΠΊΠ° Π΄ΠΎΠ»ΠΆΠ½Π° ΡΠ°ΡΠΏΠΎΠ»Π°Π³Π°ΡΡΡΡ ΠΏΡΠ°Π²Π΅Π΅ (ΠΈΠΌΠ΅ΡΡ Π±ΠΎΠ»ΡΡΠΈΠΉ Π½ΠΎΠΌΠ΅Ρ) Π»ΡΠ±ΠΎΠΉ Π·Π°Π½ΡΡΠΎΠΉ.
ΠΠ°ΠΌ Π½Π΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΠΎ Π½Π°ΠΉΡΠΈ ΠΌΠΈΠ½ΠΈΠΌΠ°Π»ΡΠ½ΠΎΠ΅ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΠΎΠΏΠ΅ΡΠ°ΡΠΈΠΉ ΠΏΠ΅ΡΠ΅ΠΏΠΈΡΡΠ²Π°Π½ΠΈΡ Π΄Π°Π½Π½ΡΡ
ΠΈΠ· ΠΎΠ΄Π½ΠΎΠΉ ΡΡΠ΅ΠΉΠΊΠΈ Π² Π΄ΡΡΠ³ΡΡ, Ρ ΠΏΠΎΠΌΠΎΡΡΡ ΠΊΠΎΡΠΎΡΡΡ
ΠΌΠΎΠΆΠ½ΠΎ Π΄ΠΎΡΡΠΈΡΡ ΠΎΠΏΠΈΡΠ°Π½Π½ΡΡ
ΡΡΠ»ΠΎΠ²ΠΈΠΉ. ΠΠΎΠΏΡΡΡΠΈΠΌΠΎ, ΡΡΠΎ ΠΎΡΠ½ΠΎΡΠΈΡΠ΅Π»ΡΠ½ΡΠΉ ΠΏΠΎΡΡΠ΄ΠΎΠΊ ΡΡΠ΅Π΅ΠΊ Π² ΠΏΠ°ΠΌΡΡΠΈ Π΄Π»Ρ ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ ΠΈΠ· ΠΏΡΠΎΡΠ΅ΡΡΠΎΠ² ΠΈΠ·ΠΌΠ΅Π½ΠΈΡΡΡ ΠΏΠΎΡΠ»Π΅ Π΄Π΅ΡΡΠ°Π³ΠΌΠ΅Π½ΡΠ°ΡΠΈΠΈ, Π½ΠΎ ΠΎΡΠ½ΠΎΡΠΈΡΠ΅Π»ΡΠ½ΡΠΉ ΠΏΠΎΡΡΠ΄ΠΎΠΊ ΡΠ°ΠΌΠΈΡ
ΠΏΡΠΎΡΠ΅ΡΡΠΎΠ² Π΄ΠΎΠ»ΠΆΠ΅Π½ ΠΎΡΡΠ°ΡΡΡΡ Π±Π΅Π· ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΉ. ΠΡΠΎ Π·Π½Π°ΡΠΈΡ, ΡΡΠΎ Π΅ΡΠ»ΠΈ Π²ΡΠ΅ ΡΡΠ΅ΠΉΠΊΠΈ, ΠΏΡΠΈΠ½Π°Π΄Π»Π΅ΠΆΠ°ΡΠΈΠ΅ ΠΏΡΠΎΡΠ΅ΡΡΡ i, Π½Π°Ρ
ΠΎΠ΄ΠΈΠ»ΠΈΡΡ Π² ΠΏΠ°ΠΌΡΡΠΈ ΡΠ°Π½ΡΡΠ΅ Π²ΡΠ΅Ρ
ΡΡΠ΅Π΅ΠΊ ΠΏΡΠΎΡΠ΅ΡΡΠ° j, ΡΠΎ ΠΈ ΠΏΠΎΡΠ»Π΅ ΠΏΠ΅ΡΠ΅ΠΌΠ΅ΡΠ΅Π½ΠΈΠΉ ΡΡΠΎ ΡΡΠ»ΠΎΠ²ΠΈΠ΅ Π΄ΠΎΠ»ΠΆΠ½ΠΎ Π²ΡΠΏΠΎΠ»Π½ΡΡΡΡΡ.
Π‘ΡΠΈΡΠ°ΠΉΡΠ΅, ΡΡΠΎ Π½ΠΎΠΌΠ΅ΡΠ° Π²ΡΠ΅Ρ
ΠΏΡΠΎΡΠ΅ΡΡΠΎΠ² ΡΠ½ΠΈΠΊΠ°Π»ΡΠ½Ρ, Ρ
ΠΎΡΡ Π±Ρ ΠΎΠ΄Π½Π° ΡΡΠ΅ΠΉΠΊΠ° ΠΏΠ°ΠΌΡΡΠΈ Π·Π°Π½ΡΡΠ° ΠΊΠ°ΠΊΠΈΠΌ-Π»ΠΈΠ±ΠΎ ΠΏΡΠΎΡΠ΅ΡΡΠΎΠΌ.
-----ΠΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅-----
Π ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΡΠΎΠΊΠ΅ Π²Ρ
ΠΎΠ΄Π½ΡΡ
Π΄Π°Π½Π½ΡΡ
Π·Π°ΠΏΠΈΡΠ°Π½ΠΎ ΡΠΈΡΠ»ΠΎ n (1 β€ n β€ 200 000)Β β ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΡΠ΅Π΅ΠΊ Π² ΠΏΠ°ΠΌΡΡΠΈ ΠΊΠΎΠΌΠΏΡΡΡΠ΅ΡΠ°.
ΠΠΎ Π²ΡΠΎΡΠΎΠΉ ΡΡΡΠΎΠΊΠ΅ Π²Ρ
ΠΎΠ΄Π½ΡΡ
Π΄Π°Π½Π½ΡΡ
ΡΠ»Π΅Π΄ΡΡΡ n ΡΠ΅Π»ΡΡ
ΡΠΈΡΠ΅Π» a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ n), Π³Π΄Π΅ a_{i} ΡΠ°Π²Π½ΠΎ Π»ΠΈΠ±ΠΎ 0 (ΡΡΠΎ ΠΎΠ·Π½Π°ΡΠ°Π΅Ρ, ΡΡΠΎ i-Ρ ΡΡΠ΅ΠΉΠΊΠ° ΠΏΠ°ΠΌΡΡΠΈ ΡΠ²ΠΎΠ±ΠΎΠ΄Π½Π°), Π»ΠΈΠ±ΠΎ Π½ΠΎΠΌΠ΅ΡΡ ΠΏΡΠΎΡΠ΅ΡΡΠ°, ΠΊΠΎΡΠΎΡΠΎΠΌΡ ΠΏΡΠΈΠ½Π°Π΄Π»Π΅ΠΆΠΈΡ i-Ρ ΡΡΠ΅ΠΉΠΊΠ° ΠΏΠ°ΠΌΡΡΠΈ. ΠΠ°ΡΠ°Π½ΡΠΈΡΡΠ΅ΡΡΡ, ΡΡΠΎ Ρ
ΠΎΡΡ Π±Ρ ΠΎΠ΄Π½ΠΎ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ a_{i} Π½Π΅ ΡΠ°Π²Π½ΠΎ 0.
ΠΡΠΎΡΠ΅ΡΡΡ ΠΏΡΠΎΠ½ΡΠΌΠ΅ΡΠΎΠ²Π°Π½Ρ ΡΠ΅Π»ΡΠΌΠΈ ΡΠΈΡΠ»Π°ΠΌΠΈ ΠΎΡ 1 Π΄ΠΎ n Π² ΠΏΡΠΎΠΈΠ·Π²ΠΎΠ»ΡΠ½ΠΎΠΌ ΠΏΠΎΡΡΠ΄ΠΊΠ΅. ΠΡΠΈ ΡΡΠΎΠΌ ΠΏΡΠΎΡΠ΅ΡΡΡ Π½Π΅ ΠΎΠ±ΡΠ·Π°ΡΠ΅Π»ΡΠ½ΠΎ ΠΏΡΠΎΠ½ΡΠΌΠ΅ΡΠΎΠ²Π°Π½Ρ ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΡΠΌΠΈ ΡΠΈΡΠ»Π°ΠΌΠΈ.
-----ΠΡΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅-----
ΠΡΠ²Π΅Π΄ΠΈΡΠ΅ ΠΎΠ΄Π½ΠΎ ΡΠ΅Π»ΠΎΠ΅ ΡΠΈΡΠ»ΠΎΒ β ΠΌΠΈΠ½ΠΈΠΌΠ°Π»ΡΠ½ΠΎΠ΅ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΠΎΠΏΠ΅ΡΠ°ΡΠΈΠΉ, ΠΊΠΎΡΠΎΡΠΎΠ΅ Π½ΡΠΆΠ½ΠΎ ΡΠ΄Π΅Π»Π°ΡΡ Π΄Π»Ρ Π΄Π΅ΡΡΠ°Π³ΠΌΠ΅Π½ΡΠ°ΡΠΈΠΈ ΠΏΠ°ΠΌΡΡΠΈ.
-----ΠΡΠΈΠΌΠ΅ΡΡ-----
ΠΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅
4
0 2 2 1
ΠΡΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅
2
ΠΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅
8
0 8 8 8 0 4 4 2
ΠΡΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅
4
-----ΠΡΠΈΠΌΠ΅ΡΠ°Π½ΠΈΠ΅-----
Π ΠΏΠ΅ΡΠ²ΠΎΠΌ ΡΠ΅ΡΡΠΎΠ²ΠΎΠΌ ΠΏΡΠΈΠΌΠ΅ΡΠ΅ Π΄ΠΎΡΡΠ°ΡΠΎΡΠ½ΠΎ Π΄Π²ΡΡ
ΠΎΠΏΠ΅ΡΠ°ΡΠΈΠΉ: ΠΠ΅ΡΠ΅ΠΏΠΈΡΠ°ΡΡ Π΄Π°Π½Π½ΡΠ΅ ΠΈΠ· ΡΡΠ΅ΡΡΠ΅ΠΉ ΡΡΠ΅ΠΉΠΊΠΈ Π² ΠΏΠ΅ΡΠ²ΡΡ. ΠΠΎΡΠ»Π΅ ΡΡΠΎΠ³ΠΎ ΠΏΠ°ΠΌΡΡΡ ΠΊΠΎΠΌΠΏΡΡΡΠ΅ΡΠ° ΠΏΡΠΈΠΌΠ΅Ρ Π²ΠΈΠ΄: 2Β 2Β 0Β 1. ΠΠ΅ΡΠ΅ΠΏΠΈΡΠ°ΡΡ Π΄Π°Π½Π½ΡΠ΅ ΠΈΠ· ΡΠ΅ΡΠ²Π΅ΡΡΠΎΠΉ ΡΡΠ΅ΠΉΠΊΠΈ Π² ΡΡΠ΅ΡΡΡ. ΠΠΎΡΠ»Π΅ ΡΡΠΎΠ³ΠΎ ΠΏΠ°ΠΌΡΡΡ ΠΊΠΎΠΌΠΏΡΡΡΠ΅ΡΠ° ΠΏΡΠΈΠΌΠ΅Ρ Π²ΠΈΠ΄: 2Β 2Β 1Β 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.
Create a function `close_compare` that accepts 3 parameters: `a`, `b`, and an optional `margin`. The function should return whether `a` is lower than, close to, or higher than `b`. `a` is "close to" `b` if `margin` is higher than or equal to the difference between `a` and `b`.
When `a` is lower than `b`, return `-1`.
When `a` is higher than `b`, return `1`.
When `a` is close to `b`, return `0`.
If `margin` is not given, treat it as zero.
Example: if `a = 3`, `b = 5` and the `margin = 3`, since `a` and `b` are no more than 3 apart, `close_compare` should return `0`. Otherwise, if instead `margin = 0`, `a` is lower than `b` and `close_compare` should return `-1`.
Assume: `margin >= 0`
Tip: Some languages have a way to make arguments optional.
Write your solution by modifying this code:
```python
def close_compare(a, b, margin=0):
```
Your solution should implemented in the function "close_compare". 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.
Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.
More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.
<image>
It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.
You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n Γ m in size.
Input
The first line contains two integers n and m (2 β€ n, m β€ 106).
Output
Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other.
Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).
Examples
Input
3 4
Output
2
Input
3 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.
Panic is rising in the committee for doggo standardizationΒ β the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.
The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.
Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color $x$ such that there are currently at least two puppies of color $x$ and recolor all puppies of the color $x$ into some arbitrary color $y$. Luckily, this operation can be applied multiple times (including zero).
For example, if the number of puppies is $7$ and their colors are represented as the string "abababc", then in one operation Slava can get the results "zbzbzbc", "bbbbbbc", "aaaaaac", "acacacc" and others. However, if the current color sequence is "abababc", then he can't choose $x$='c' right now, because currently only one puppy has the color 'c'.
Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$)Β β the number of puppies.
The second line contains a string $s$ of length $n$ consisting of lowercase Latin letters, where the $i$-th symbol denotes the $i$-th puppy's color.
-----Output-----
If it's possible to recolor all puppies into one color, print "Yes".
Otherwise print "No".
Output the answer without quotation signs.
-----Examples-----
Input
6
aabddc
Output
Yes
Input
3
abc
Output
No
Input
3
jjj
Output
Yes
-----Note-----
In the first example Slava can perform the following steps: take all puppies of color 'a' (a total of two) and recolor them into 'b'; take all puppies of color 'd' (a total of two) and recolor them into 'c'; take all puppies of color 'b' (three puppies for now) and recolor them into 'c'.
In the second example it's impossible to recolor any of the puppies.
In the third example all the puppies' colors are the same; thus there's no need to recolor anything.
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 loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin letters. String w has the length of |w|, its characters are numbered from 1 to |w|.
First Petya should find all the occurrences of forbidden substrings in the w string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.
After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position i should be replaced by any other one if for position i in string w there exist pair of indices l, r (1 β€ l β€ i β€ r β€ |w|) such that substring w[l ... r] is contained in the collection s1, s2, ..., sn, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.
Letter letter (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the letter occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.
Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.
Input
The first line contains the only integer n (1 β€ n β€ 100) β the number of forbidden substrings in the collection. Next n lines contain these substrings. The next line contains string w. All those n + 1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter letter.
Output
Output the only line β Petya's resulting string with the maximum number of letters letter. If there are several answers then output the one that comes first lexicographically.
The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if a is a prefix of b, or there exists such an i (1 β€ i β€ |a|), that ai < bi, and for any j (1 β€ j < i) aj = bj. |a| stands for the length of string a.
Examples
Input
3
bers
ucky
elu
PetrLoveLuckyNumbers
t
Output
PetrLovtTttttNumtttt
Input
4
hello
party
abefglghjdhfgj
IVan
petrsmatchwin
a
Output
petrsmatchwin
Input
2
aCa
cba
abAcaba
c
Output
abCacba
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: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
Example:
``` ruby
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'
list([ {name: 'Bart'}, {name: 'Lisa'} ])
# returns 'Bart & Lisa'
list([ {name: 'Bart'} ])
# returns 'Bart'
list([])
# returns ''
```
``` elixir
list([ %{name: "Bart"}, %{name: "Lisa"}, %{name: "Maggie"} ])
# returns 'Bart, Lisa & Maggie'
list([ %{name: "Bart"}, %{name: "Lisa"} ])
# returns 'Bart & Lisa'
list([ %{name: "Bart"} ])
# returns 'Bart'
list([])
# returns ''
```
``` javascript
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'
list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'
list([ {name: 'Bart'} ])
// returns 'Bart'
list([])
// returns ''
```
```python
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'
namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])
# returns 'Bart & Lisa'
namelist([ {'name': 'Bart'} ])
# returns 'Bart'
namelist([])
# returns ''
```
Note: all the hashes are pre-validated and will only contain A-Z, a-z, '-' and '.'.
Write your solution by modifying this code:
```python
def namelist(names):
```
Your solution should implemented in the function "namelist". 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 a directed graph consisting of $n$ vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty.
You should process $m$ queries with it. Each query is one of three types:
"$+$ $u$ $v$ $c$" β add arc from $u$ to $v$ with label $c$. It's guaranteed that there is no arc $(u, v)$ in the graph at this moment;
"$-$ $u$ $v$" β erase arc from $u$ to $v$. It's guaranteed that the graph contains arc $(u, v)$ at this moment;
"$?$ $k$" β find the sequence of $k$ vertices $v_1, v_2, \dots, v_k$ such that there exist both routes $v_1 \to v_2 \to \dots \to v_k$ and $v_k \to v_{k - 1} \to \dots \to v_1$ and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times.
-----Input-----
The first line contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$; $1 \le m \le 2 \cdot 10^5$) β the number of vertices in the graph and the number of queries.
The next $m$ lines contain queries β one per line. Each query is one of three types:
"$+$ $u$ $v$ $c$" ($1 \le u, v \le n$; $u \neq v$; $c$ is a lowercase Latin letter);
"$-$ $u$ $v$" ($1 \le u, v \le n$; $u \neq v$);
"$?$ $k$" ($2 \le k \le 10^5$).
It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type.
-----Output-----
For each query of the third type, print YES if there exist the sequence $v_1, v_2, \dots, v_k$ described above, or NO otherwise.
-----Examples-----
Input
3 11
+ 1 2 a
+ 2 3 b
+ 3 2 a
+ 2 1 b
? 3
? 2
- 2 1
- 3 2
+ 2 1 c
+ 3 2 d
? 5
Output
YES
NO
YES
-----Note-----
In the first query of the third type $k = 3$, we can, for example, choose a sequence $[1, 2, 3]$, since $1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3$ and $3 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 1$.
In the second query of the third type $k = 2$, and we can't find sequence $p_1, p_2$ such that arcs $(p_1, p_2)$ and $(p_2, p_1)$ have the same characters.
In the third query of the third type, we can, for example, choose a sequence $[1, 2, 3, 2, 1]$, where $1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3 \xrightarrow{\text{d}} 2 \xrightarrow{\text{c}} 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.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "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.
Story
Jumbo Juice makes a fresh juice out of fruits of your choice.Jumbo Juice charges $5 for regular fruits and $7 for special ones. Regular fruits are Banana, Orange, Apple, Lemon and Grapes. Special ones are Avocado, Strawberry and Mango. Others fruits that are not listed are also available upon request. Those extra special fruits cost $9 per each. There is no limit on how many fruits she/he picks.The price of a cup of juice is the mean of price of chosen fruits. In case of decimal number (ex. $5.99), output should be the nearest integer (use the standard rounding function of your language of choice).
Input
The function will receive an array of strings, each with the name of a fruit. The recognition of names should be case insensitive. There is no case of an enmpty array input.
Example
```
['Mango', 'Banana', 'Avocado'] //the price of this juice bottle is (7+5+7)/3 = $6($6.333333...)
```
Write your solution by modifying this code:
```python
def mix_fruit(arr):
```
Your solution should implemented in the function "mix_fruit". 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.
Most of this problem is by the original author of [the harder kata](https://www.codewars.com/kata/556206664efbe6376700005c), I just made it simpler.
I read a book recently, titled "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker ( [Youtube](https://www.youtube.com/user/standupmaths) ), and in the first chapter of the book Matt talks about problems he likes to solve in his head to take his mind off the fact that he is in his dentist's chair, we've all been there!
The problem he talks about relates to polydivisible numbers, and I thought a kata should be written on the subject as it's quite interesting. (Well it's interesting to me, so there!)
### Polydivisib... huh what?
So what are they?
A polydivisible number is divisible in an unusual way. The first digit is cleanly divisible by `1`, the first two digits are cleanly divisible by `2`, the first three by `3`, and so on.
### Examples
Let's take the number `1232` as an example.
```
1 / 1 = 1 // Works
12 / 2 = 6 // Works
123 / 3 = 41 // Works
1232 / 4 = 308 // Works
```
`1232` is a polydivisible number.
However, let's take the number `123220` and see what happens.
```
1 /1 = 1 // Works
12 /2 = 6 // Works
123 /3 = 41 // Works
1232 /4 = 308 // Works
12322 /5 = 2464.4 // Doesn't work
123220 /6 = 220536.333... // Doesn't work
```
`123220` is not polydivisible.
### Your job: check if a number is polydivisible or not.
Return `true` if it is, and `false` if it isn't.
Note: All inputs will be valid numbers between `0` and `2^53-1 (9,007,199,254,740,991)` (inclusive).
Note: All single digit numbers (including `0`) are trivially polydivisible.
Note: Except for `0`, no numbers will start with `0`.
Write your solution by modifying this code:
```python
def polydivisible(x):
```
Your solution should implemented in the function "polydivisible". 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.
Berland Football Cup starts really soon! Commentators from all over the world come to the event.
Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.
If $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment.
Organizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.
What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)?
-----Input-----
The only line contains four integer numbers $n$, $m$, $a$ and $b$ ($1 \le n, m \le 10^{12}$, $1 \le a, b \le 100$), where $n$ is the initial number of the commentary boxes, $m$ is the number of delegations to come, $a$ is the fee to build a box and $b$ is the fee to demolish a box.
-----Output-----
Output the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$). It is allowed that the final number of the boxes is equal to $0$.
-----Examples-----
Input
9 7 3 8
Output
15
Input
2 7 3 7
Output
14
Input
30 6 17 19
Output
0
-----Note-----
In the first example organizers can build $5$ boxes to make the total of $14$ paying $3$ burles for the each of them.
In the second example organizers can demolish $2$ boxes to make the total of $0$ paying $7$ burles for the each of them.
In the third example organizers are already able to distribute all the boxes equally among the delegations, each one get $5$ boxes.
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.
Spoonerize... with numbers... numberize?... numboonerize?... noonerize? ...anyway! If you don't yet know what a spoonerism is and haven't yet tried my spoonerism kata, please do [check it out](http://www.codewars.com/kata/spoonerize-me) first.
You will create a function which takes an array of two positive integers, spoonerizes them, and returns the positive difference between them as a single number or ```0``` if the numbers are equal:
```
[123, 456] = 423 - 156 = 267
```
Your code must test that all array items are numbers and return ```"invalid array"``` if it finds that either item is not a number. The provided array will always contain 2 elements.
When the inputs are valid, they will always be integers, no floats will be passed. However, you must take into account that the numbers will be of varying magnitude, between and within test cases.
Write your solution by modifying this code:
```python
def noonerize(numbers):
```
Your solution should implemented in the function "noonerize". 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.
From the FAQ:
What am I allowed to post as a comment for a problem?
Do NOT post code.
Do NOT post a comment asking why your solution is wrong.
Do NOT post a comment asking if you can be given the test case your program fails on.
Do NOT post a comment asking how your solution can be improved.
Do NOT post a comment giving any hints or discussing approaches to the problem, or what type or speed of algorithm is required.
------ Problem Statement ------
Chef Doom has decided to bake a circular cake. He wants to place N colored cherries around the cake in a circular manner. As all great chefs do, Doom doesn't want any two adjacent cherries to have the same color. Chef has unlimited supply of cherries of K β€ 10 different colors. Each color is denoted by the digit from the set {0, 1, ..., K β 1}. Different colors are denoted by different digits. Some of the cherries are already placed and the Chef wants you to place cherries in the remaining positions. He understands that there can be many such arrangements, so in the case when the answer is not unique he asks you to find the lexicographically smallest one.
What does it mean?
Let's numerate positions for the cherries by the numbers 1, 2, ..., N starting from one of the positions in a clockwise direction. Then the current (possibly partial) arrangement of the cherries can be represented by a string of N characters. For each position i of the arrangement if the cherry of the color C is placed at this position then the i^{th} character of the string is equal to the digit C. Otherwise, it is equal to the question mark ?. We identify the arrangement with the string that represents it.
One arrangement is called lexicographically smaller than the other arrangement if at the first position where they differ the first one has smaller digit (we compare only complete arrangements so we don't care about relation between digits and the question mark). For example, the arrangement 1230123 is lexicographically smaller than 1231230 since they have first 3 equal characters but the 4^{th} character in the first arrangement is 0 and it is less than 1 which is the 4^{th} character of the second arrangement.
Notes
The cherries at the first and the last positions are adjacent to each other (recall that we have a circular cake).
In the case N = 1 any arrangement is valid as long as the color used for the only cherry of this arrangement is less than K.
Initial arrangement can be already invalid (see the case 3 in the example).
Just to make all things clear. You will be given a usual string of digits and question marks. Don't be confused by circular stuff we have in this problem. You don't have to rotate the answer once you have replaced all question marks by the digits. Think of the output like the usual string for which each two consecutive digits must be different but having additional condition that the first and the last digits must be also different (of course if N > 1).
Next, you don't have to use all colors. The only important condition is that this string should be lexicographically smaller than all other strings that can be obtained from the input string by replacement of question marks by digits and of course it must satisfy conditions on adjacent digits.
One more thing, K here is not the length of the string but the number of allowed colors. Also we emphasize that the given string can have arbitrary number of question marks. So it can have zero number of question marks as well as completely consists of question marks but of course in general situation it can have both digits and question marks.
OK. Let's try to formalize things in order to make all even more clear. You will be given an integer K and a string S=S[1]S[2]...S[N] where each S[i] is either the decimal digit less than K or the question mark. We are serious. In all tests string S can have only digits less than K. Don't ask about what to do if we have digit β₯ K. There are no such tests at all! We guarantee this! OK, let's continue. Your task is to replace each question mark by some digit strictly less than K. If there were no question marks in the string skip this step. Now if N=1 then your string is already valid. For N > 1 it must satisfy the following N conditions S[1] β S[2], S[2] β S[3], ..., S[N-1] β S[N], S[N] β S[1]. Among all such valid strings that can be obtained by replacement of question marks you should choose lexicographically smallest one. I hope now the problem is really clear.
------ Input ------
The first line of the input file contains an integer T, the number of test cases. T test cases follow. Each test case consists of exactly two lines. The first line contains an integer K, the number of available colors for cherries. The second line contains a string S that represents the current arrangement of the cherries in the cake.
------ Constraints ------
1 β€ T β€ 1000
1 β€ K β€ 10
1 β€ |S| β€ 100, where |S| denotes the length of the string S
Each character in S is either the digit from the set {0, 1, ..., K β 1} or the question mark ?
------ Output ------
For each test case output the lexicographically smallest valid arrangement of the cherries in the cake that can be obtained from the given arrangement by replacement of each question mark by some digit from 0 to K β 1. If it is impossible to place the cherries output NO (output is case sensitive).
----- Sample Input 1 ------
7
1
?
2
?0
10
79259?087
2
??
3
0?1
4
?????
3
012
----- Sample Output 1 ------
0
10
NO
01
021
01012
012
----- explanation 1 ------
Case 2. The only possible replacement here is 10. Note that we output 10 since we can not rotate the answer to obtain 01 which is smaller.
Case 3. Arrangement is impossible because cherries at the first and the last positions are already of the same color. Note that K = 10 but the string has length 9. It is normal. K and |S| don't have any connection.
Case 4. There are two possible arrangements: 01 and 10. The answer is the first one since it is lexicographically smaller.
Case 5. There are three possible ways to replace question mark by the digit: 001, 011 and 021. But the first and the second strings are not valid arrangements as in both of them there exists an adjacent pair of cherries having the same color. Hence the answer is the third string.
Case 6. Note that here we do not use all colors. We just find the lexicographically smallest string that satisfies condition on adjacent digit.
Case 7. The string is already valid arrangement of digits. Hence we simply print the same string to the output.
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.
Daniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session.
The game involves $n$ players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how many balls were involved during the game. The only thing he knows is the number of passes delivered by each player during all the session.
Find the minimum possible amount of balls that were involved in the game.
-----Input-----
There are several test cases in the input data. The first line contains a single integer $t$ ($1 \leq t \leq 5 \cdot 10^4$) β the number of test cases. This is followed by the test cases description.
The first line of each test case contains one integer $n$ ($2 \leq n \leq 10^5$) β the number of players.
The second line of the test case contains a sequence of integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 10^9$), where $a_i$ is the number of passes delivered by the $i$-th player.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case print a single integer β the answer to the problem.
-----Examples-----
Input
4
4
2 3 3 2
3
1 5 2
2
0 0
4
1000000000 1000000000 1000000000 1000000000
Output
1
2
0
1
-----Note-----
In the first test case, with the only ball, the game can go like this:
$2 \rightarrow 1 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2$.
In the second test case, there is no possible way to play the game with only one ball. One possible way to play with two balls:
$2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1$.
$2 \rightarrow 3 \rightarrow 2 \rightarrow 1$
In the third example, there were no passes, so $0$ balls are possible.
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.
Hakone Ekiden is one of the Japanese New Year's traditions. In Hakone Ekiden, 10 runners from each team aim for the goal while connecting the sashes at each relay station. In the TV broadcast, the ranking change from the previous relay station is displayed along with the passing order of each team at the relay station. So, look at it and tell us how many possible passage orders for each team at the previous relay station. The number of possible transit orders can be very large, so answer by the remainder divided by 1,000,000,007.
Input
The input is given in the form:
> n
> c1
> c2
> ...
> cn
>
The number n (1 β€ n β€ 200) representing the number of teams is on the first line, and the ranking changes from the previous relay station in order from the first place on the following n lines. If it is'`U`', the ranking is up, if it is'`-`', the ranking is not changed) is written.
Output
Please output in one line by dividing the number of passages that could have been the previous relay station by 1,000,000,007.
Examples
Input
3
-
U
D
Output
1
Input
5
U
U
-
D
D
Output
5
Input
8
U
D
D
D
D
D
D
D
Output
1
Input
10
U
D
U
D
U
D
U
D
U
D
Output
608
Input
2
D
U
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.
For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.
Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.
Find the maximum possible value of M_1 + M_2 + \cdots + M_N.
-----Constraints-----
- N is an integer satisfying 1 \leq N \leq 10^9.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the maximum possible value of M_1 + M_2 + \cdots + M_N.
-----Sample Input-----
2
-----Sample Output-----
1
When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 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.
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.
One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.
Input
The only line contains a positive integer n (1 β€ n β€ 109). This number doesn't have leading zeroes.
Output
Output the least super lucky number that is more than or equal to n.
Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
4500
Output
4747
Input
47
Output
47
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(n) denote the sum of the digits in the decimal notation of n.
For example, S(123) = 1 + 2 + 3 = 6.
We will call an integer n a Snuke number when, for all positive integers m such that m > n, \frac{n}{S(n)} \leq \frac{m}{S(m)} holds.
Given an integer K, list the K smallest Snuke numbers.
-----Constraints-----
- 1 \leq K
- The K-th smallest Snuke number is not greater than 10^{15}.
-----Input-----
Input is given from Standard Input in the following format:
K
-----Output-----
Print K lines. The i-th line should contain the i-th smallest Snuke number.
-----Sample Input-----
10
-----Sample Output-----
1
2
3
4
5
6
7
8
9
19
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've just recently been hired to calculate scores for a Dart Board game!
Scoring specifications:
* 0 points - radius above 10
* 5 points - radius between 5 and 10 inclusive
* 10 points - radius less than 5
**If all radii are less than 5, award 100 BONUS POINTS!**
Write a function that accepts an array of radii (can be integers and/or floats), and returns a total score using the above specification.
An empty array should return 0.
## Examples:
Write your solution by modifying this code:
```python
def score_throws(radii):
```
Your solution should implemented in the function "score_throws". 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.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
-----Input-----
The first line contains integer n (2 β€ n β€ 2Β·10^5) β the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers a_{i}, b_{i} (0 β€ a_{i}, b_{i} β€ 10^6), where a_{i} is the ID number of a person in front of a student and b_{i} is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
-----Output-----
Print a sequence of n integers x_1, x_2, ..., x_{n} β the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
-----Examples-----
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
-----Note-----
The picture illustrates the queue for the first sample. [Image]
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_1, a_2, \dots , a_n$. Array is good if for each pair of indexes $i < j$ the condition $j - a_j \ne i - a_i$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if $a = [1, 1, 3, 5]$, then shuffled arrays $[1, 3, 5, 1]$, $[3, 5, 1, 1]$ and $[5, 3, 1, 1]$ are good, but shuffled arrays $[3, 1, 5, 1]$, $[1, 1, 3, 5]$ and $[1, 1, 5, 3]$ aren't.
It's guaranteed that it's always possible to shuffle an array to meet this condition.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) β the number of test cases.
The first line of each test case contains one integer $n$ ($1 \le n \le 100$) β the length of array $a$.
The second line of each test case contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le 100$).
-----Output-----
For each test case print the shuffled version of the array $a$ which is good.
-----Example-----
Input
3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
Output
7
1 5 1 3
2 4 6 1 3 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 a coordinate system,There are 3 chocolate which will be placed at three random position (x1,y1),(x2,y2) and (x3,y3).Ramesh loves Chocolates. Ramesh always moves along a straight line. your task is to find out whether he can have all the chocolates.
Input Format :-
The first line of the input contains an integer T denoting the number of test cases. Each of the next T lines contains coordinates in integer- x1 y1 x2 y2 and x3 y3.
Output Format :-
If Ramesh can get all chocolates then print "YES" otherwise "NO"(without quotes).
Constraints :-
1 β€ T β€ 100
-1000 β€ x1,y1,x2,y2,x3,y3 β€ 1000
SAMPLE INPUT
2
1 1 2 2 3 3
1 2 5 4 10 15
SAMPLE OUTPUT
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.
Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives a_{i} hits.
Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.
-----Input-----
The first line contains three integers n,x,y (1 β€ n β€ 10^5, 1 β€ x, y β€ 10^6) β the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly.
Next n lines contain integers a_{i} (1 β€ a_{i} β€ 10^9)Β β the number of hits needed do destroy the i-th monster.
-----Output-----
Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time.
-----Examples-----
Input
4 3 2
1
2
3
4
Output
Vanya
Vova
Vanya
Both
Input
2 1 1
1
2
Output
Both
Both
-----Note-----
In the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1.
In the second sample Vanya and Vova make the first and second hit simultaneously at time 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.
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ starting from the $l$-th character and ending with the $r$-th character as $s[l \dots r]$. The characters of each string are numbered from $1$.
We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.
Binary string $a$ is considered reachable from binary string $b$ if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1 = a$, $s_k = b$, and for every $i \in [1, k - 1]$, $s_i$ can be transformed into $s_{i + 1}$ using exactly one operation. Note that $k$ can be equal to $1$, i. e., every string is reachable from itself.
You are given a string $t$ and $q$ queries to it. Each query consists of three integers $l_1$, $l_2$ and $len$. To answer each query, you have to determine whether $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the length of string $t$.
The second line contains one string $t$ ($|t| = n$). Each character of $t$ is either 0 or 1.
The third line contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) β the number of queries.
Then $q$ lines follow, each line represents a query. The $i$-th line contains three integers $l_1$, $l_2$ and $len$ ($1 \le l_1, l_2 \le |t|$, $1 \le len \le |t| - \max(l_1, l_2) + 1$) for the $i$-th query.
-----Output-----
For each query, print either YES if $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$, or NO otherwise. You may print each letter in any register.
-----Example-----
Input
5
11011
3
1 3 3
1 4 2
1 2 3
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.
A category page displays a set number of products per page, with pagination at the bottom allowing the user to move from page to page.
Given that you know the page you are on, how many products are in the category in total, and how many products are on any given page, how would you output a simple string showing which products you are viewing..
examples
In a category of 30 products with 10 products per page, on page 1 you would see
'Showing 1 to 10 of 30 Products.'
In a category of 26 products with 10 products per page, on page 3 you would see
'Showing 21 to 26 of 26 Products.'
In a category of 8 products with 10 products per page, on page 1 you would see
'Showing 1 to 8 of 8 Products.'
Write your solution by modifying this code:
```python
def pagination_text(page_number, page_size, total_products):
```
Your solution should implemented in the function "pagination_text". 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.
# Description:
Find the longest successive exclamation marks and question marks combination in the string. A successive exclamation marks and question marks combination must contains two part: a substring of "!" and a substring "?", they are adjacent.
If more than one result are found, return the one which at left side; If no such a combination found, return `""`.
# Examples
```
find("!!") === ""
find("!??") === "!??"
find("!?!!") === "?!!"
find("!!???!????") === "!!???"
find("!!???!?????") === "!?????"
find("!????!!!?") === "????!!!"
find("!?!!??!!!?") === "??!!!"
```
# Note
Please don't post issue about difficulty or duplicate. Because:
>[That's unfair on the kata creator. This is a valid kata and introduces new people to javascript some regex or loops, depending on how they tackle this problem. --matt c](https://www.codewars.com/kata/remove-exclamation-marks/discuss#57fabb625c9910c73000024e)
Write your solution by modifying this code:
```python
def find(s):
```
Your solution should implemented in the function "find". 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.
A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 β€ k1 < k2 < ... < k|x| β€ |s|).
You've got two strings β s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 β€ i β€ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 β€ j β€ |x|) kj = i.
Input
The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105.
Output
Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise.
Examples
Input
abab
ab
Output
Yes
Input
abacaba
aba
Output
No
Input
abc
ba
Output
No
Note
In the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once.
In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t.
In the third sample there is no occurrence of string t in string s.
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.
Nukes has an integer that can be represented as the bitwise OR of one or more integers between A and B (inclusive). How many possible candidates of the value of Nukes's integer there are?
Constraints
* 1 β€ A β€ B < 2^{60}
* A and B are integers.
Input
The input is given from Standard Input in the following format:
A
B
Output
Print the number of possible candidates of the value of Nukes's integer.
Examples
Input
7
9
Output
4
Input
65
98
Output
63
Input
271828182845904523
314159265358979323
Output
68833183630578410
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 ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP.
In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed.
The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca".
Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland.
Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters.
Output
Print a single number β length of the sought dynasty's name in letters.
If Vasya's list is wrong and no dynasty can be found there, print a single number 0.
Examples
Input
3
abc
ca
cba
Output
6
Input
4
vvp
vvp
dam
vvp
Output
0
Input
3
ab
c
def
Output
1
Note
In the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings).
In the second sample there aren't acceptable dynasties.
The only dynasty in the third sample consists of one king, his name is "c".
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've got a positive integer sequence a_1, a_2, ..., a_{n}. All numbers in the sequence are distinct. Let's fix the set of variables b_1, b_2, ..., b_{m}. Initially each variable b_{i} (1 β€ i β€ m) contains the value of zero. Consider the following sequence, consisting of n operations.
The first operation is assigning the value of a_1 to some variable b_{x} (1 β€ x β€ m). Each of the following n - 1 operations is assigning to some variable b_{y} the value that is equal to the sum of values that are stored in the variables b_{i} and b_{j} (1 β€ i, j, y β€ m). At that, the value that is assigned on the t-th operation, must equal a_{t}. For each operation numbers y, i, j are chosen anew.
Your task is to find the minimum number of variables m, such that those variables can help you perform the described sequence of operations.
-----Input-----
The first line contains integer n (1 β€ n β€ 23). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 β€ a_{k} β€ 10^9).
It is guaranteed that all numbers in the sequence are distinct.
-----Output-----
In a single line print a single number β the minimum number of variables m, such that those variables can help you perform the described sequence of operations.
If you cannot perform the sequence of operations at any m, print -1.
-----Examples-----
Input
5
1 2 3 6 8
Output
2
Input
3
3 6 5
Output
-1
Input
6
2 4 8 6 10 18
Output
3
-----Note-----
In the first sample, you can use two variables b_1 and b_2 to perform the following sequence of operations. b_1 := 1; b_2 := b_1 + b_1; b_1 := b_1 + b_2; b_1 := b_1 + b_1; b_1 := b_1 + b_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.
The surveyor starship Hakodate-maru is famous for her two fuel containers with unbounded capacities. They hold the same type of atomic fuel balls.
There, however, is an inconvenience. The shapes of the fuel containers #1 and #2 are always cubic and regular tetrahedral respectively. Both of the fuel containers should be either empty or filled according to their shapes. Otherwise, the fuel balls become extremely unstable and may explode in the fuel containers. Thus, the number of fuel balls for the container #1 should be a cubic number (n3 for some n = 0, 1, 2, 3,... ) and that for the container #2 should be a tetrahedral number ( n(n + 1)(n + 2)/6 for some n = 0, 1, 2, 3,... ).
Hakodate-maru is now at the star base Goryokaku preparing for the next mission to create a precise and detailed chart of stars and interstellar matters. Both of the fuel containers are now empty. Commander Parus of Goryokaku will soon send a message to Captain Future of Hakodate-maru on how many fuel balls Goryokaku can supply. Captain Future should quickly answer to Commander Parus on how many fuel balls she requests before her ship leaves Goryokaku. Of course, Captain Future and her omcers want as many fuel balls as possible.
For example, consider the case Commander Parus offers 151200 fuel balls. If only the fuel container #1 were available (i.e. ifthe fuel container #2 were unavailable), at most 148877 fuel balls could be put into the fuel container since 148877 = 53 Γ 53 Γ 53 < 151200 < 54 Γ 54 Γ 54 . If only the fuel container #2 were available, at most 147440 fuel balls could be put into the fuel container since 147440 = 95 Γ 96 Γ 97/6 < 151200 < 96 Γ 97 Γ 98/6 . Using both of the fuel containers #1 and #2, 151200 fuel balls can be put into the fuel containers since 151200 = 39 Γ 39 Γ 39 + 81 Γ 82 Γ 83/6 . In this case, Captain Future's answer should be "151200".
Commander Parus's offer cannot be greater than 151200 because of the capacity of the fuel storages of Goryokaku. Captain Future and her omcers know that well.
You are a fuel engineer assigned to Hakodate-maru. Your duty today is to help Captain Future with calculating the number of fuel balls she should request.
Input
The input is a sequence of at most 1024 positive integers. Each line contains a single integer. The sequence is followed by a zero, which indicates the end of data and should not be treated as input. You may assume that none of the input integers is greater than 151200.
Output
The output is composed of lines, each containing a single integer. Each output integer should be the greatest integer that is the sum of a nonnegative cubic number and a nonnegative tetrahedral number and that is not greater than the corresponding input number. No other characters should appear in the output.
Example
Input
100
64
50
20
151200
0
Output
99
64
47
20
151200
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 might remember, the collector of Siruseri had ordered
a complete revision of the Voters List. He knew that constructing
the list of voters is a difficult task, prone to errors. Some
voters may have been away on vacation, others may have moved
during the enrollment and so on.
To be as accurate as possible, he entrusted the task to three different
officials. Each of them was to independently record the list of voters and
send it to the collector. In Siruseri, every one has a ID number and
the list would only list the ID numbers of the voters and not their names.
The officials were expected to arrange the ID numbers in ascending order
in their lists.
On receiving the lists, the Collector realised that there were
discrepancies - the three lists were not identical. He decided
to go with the majority. That is, he decided to construct the
final list including only those ID numbers that appeared in at
least 2 out of the 3 lists. For example if the three lists
were
23 30 42 57 90
21 23 35 57 90 92
21 23 30 57 90
then the final list compiled by the collector would be:
21 23 30 57 90
The ID numbers 35, 42 and 92 which appeared in only one list
each do not figure in the final list.
Your task is to help the collector by writing a program that
produces the final list from the three given lists.
Input format
The first line of the input contains 3 integers
N_{1}, N_{2} and
N_{3}. N_{1} is the number of
voters in the first list, N_{2} is the number of
voters in the second list and N_{3} is the number of
voters in the third list. The next N_{1} lines
(lines 2,...,N_{1}+1) contain one positive integer
each and describe the first list in ascending order. The following
N_{2} lines (lines
N_{1}+2,...,N_{1}+N_{2}+1)
describe the second list in ascending order and the final
N_{3} lines (lines
N_{1}+N_{2}+2,...,N_{1}+N_{2}+N_{3}+1)
describe the third list in ascending order.
Output format
The first line of the output should contain a single integer
M indicating the number voters in the final list. The next
M lines (lines 2,...,M+1) should contain one
positive integer each, describing the list of voters in the final
list, in ascending order.
Test data
You may assume that 1 β€
N_{1},N_{2},N_{3}
β€ 50000.
----- Sample Input 1 ------
5 6 5
23
30
42
57
90
21
23
35
57
90
92
21
23
30
57
90
----- Sample Output 1 ------
5
21
23
30
57
90
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.
Heading ##There are two integers A and B. You are required to compute the bitwise AND amongst all natural numbers lying between A and B, both inclusive.
Input Format
First line of the input contains T, the number of testcases to follow.
Each testcase in a newline contains A and B separated by a single space.
Constraints
1β€Tβ€200
0β€Aβ€B<232
Output Format
Output one line per test case with the required bitwise AND.
SAMPLE INPUT
3
12 15
2 3
8 13
SAMPLE OUTPUT
12
2
8
Explanation
1st Test Case : 12 & 13 & 14 & 15 = 12
2nd Test Case : 2 & 3 = 2
3rd Test Case : 8 & 9 & 10 & 11 & 12 & 13 = 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.
The ACM ICPC judges are very careful about not leaking their problems, and all communications are encrypted. However, one does sometimes make mistakes, like using too weak an encryption scheme. Here is an example of that.
The encryption chosen was very simple: encrypt each chunk of the input by flipping some bits according to a shared key. To provide reasonable security, the size of both chunk and key is 32 bits.
That is, suppose the input was a sequence of m 32-bit integers.
N1 N2 N3 ... Nm
After encoding with the key K it becomes the following sequence of m 32-bit integers.
(N1 β§ K) (N2 β§ K) (N3 β§ K) ... (Nm β§ K)
where (a β§ b) is the bitwise exclusive or of a and b.
Exclusive or is the logical operator which is 1 when only one of its operands is 1, and 0 otherwise. Here is its definition for 1-bit integers.
0 β 0 = 0 0 β 1 = 1
1 β 0 = 1 1 β 1 =0
As you can see, it is identical to addition modulo 2. For two 32-bit integers a and b, their bitwise exclusive or a β§ b is defined as follows, using their binary representations, composed of 0's and 1's.
a β§ b = a31 ... a1a0 β§ b31 ... b1b0 = c31 ... c1c0
where
ci = ai β bi (i = 0, 1, ... , 31).
For instance, using binary notation, 11010110 β§ 01010101 = 10100011, or using hexadecimal,
d6 β§ 55 = a3.
Since this kind of encryption is notoriously weak to statistical attacks, the message has to be compressed in advance, so that it has no statistical regularity. We suppose that N1 N2 ... Nm is already in compressed form.
However, the trouble is that the compression algorithm itself introduces some form of regularity: after every 8 integers of compressed data, it inserts a checksum, the sum of these integers. That is, in the above input, N9 = β8i=1 Ni = N1 + ... + N8, where additions are modulo 232.
Luckily, you could intercept a communication between the judges. Maybe it contains a problem for the finals!
As you are very clever, you have certainly seen that you can easily find the lowest bit of the key, denoted by K0. On the one hand, if K0 = 1, then after encoding, the lowest bit of β8i=1 Ni β§ K is unchanged, as K0 is added an even number of times, but the lowest bit of N9 β§ K is changed, so they shall differ. On the other hand, if K0 = 0, then after encoding, the lowest bit of β8i=1 Ni β§ K shall still be identical to the lowest bit of N9 β§ K, as they do not change. For instance, if the lowest bits after encoding are 1 1 1 1 1 1 1 1 1 then K0 must be 1, but if they are 1 1 1 1 1 1 1 0 1 then K0 must be 0.
So far, so good. Can you do better?
You should find the key used for encoding.
Input
The input starts with a line containing only a positive integer S, indicating the number of datasets in the input. S is no more than 1000.
It is followed by S datasets. Each dataset is composed of nine 32-bit integers corresponding to the first nine chunks of a communication. They are written in hexadecimal notation, using digits β0β to β9β and lowercase letters βaβ to βfβ, and with no leading zeros. They are separated by a space or a newline. Each dataset is ended by a newline.
Output
For each dataset you should output the key used for encoding. Each key shall appear alone on its line, and be written in hexadecimal notation, using digits β0β to β9β and lowercase letters βaβ to βfβ, and with no leading zeros.
Example
Input
8
1 1 1 1 1 1 1 1 8
3 2 3 2 3 2 3 2 6
3 4 4 7 7 b a 2 2e
e1 13 ce 28 ca 6 ab 46 a6d
b08 49e2 6128 f27 8cf2 bc50 7380 7fe1 723b
4eba eb4 a352 fd14 6ac1 eed1 dd06 bb83 392bc
ef593c08 847e522f 74c02b9c 26f3a4e1 e2720a01 6fe66007
7a4e96ad 6ee5cef6 3853cd88
60202fb8 757d6d66 9c3a9525 fbcd7983 82b9571c ddc54bab 853e52da
22047c88 e5524401
Output
0
2
6
1c6
4924afc7
ffff95c5
546991d
901c4a16
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 Little Elephant has got a problem β somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.
The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.
Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.
Input
The first line contains a single integer n (2 β€ n β€ 105) β the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, β array a.
Note that the elements of the array are not necessarily distinct numbers.
Output
In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise.
Examples
Input
2
1 2
Output
YES
Input
3
3 2 1
Output
YES
Input
4
4 3 2 1
Output
NO
Note
In the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES".
In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES".
In the third sample we can't sort the array in more than one swap operation, so the answer is "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.
Note that the memory limit in this problem is lower than in others.
You have a vertical strip with n cells, numbered consecutively from 1 to n from top to bottom.
You also have a token that is initially placed in cell n. You will move the token up until it arrives at cell 1.
Let the token be in cell x > 1 at some moment. One shift of the token can have either of the following kinds:
* Subtraction: you choose an integer y between 1 and x-1, inclusive, and move the token from cell x to cell x - y.
* Floored division: you choose an integer z between 2 and x, inclusive, and move the token from cell x to cell β x/z β (x divided by z rounded down).
Find the number of ways to move the token from cell n to cell 1 using one or more shifts, and print it modulo m. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered distinct (check example explanation for a better understanding).
Input
The only line contains two integers n and m (2 β€ n β€ 4 β
10^6; 10^8 < m < 10^9; m is a prime number) β the length of the strip and the modulo.
Output
Print the number of ways to move the token from cell n to cell 1, modulo m.
Examples
Input
3 998244353
Output
5
Input
5 998244353
Output
25
Input
42 998244353
Output
793019428
Input
787788 100000007
Output
94810539
Note
In the first test, there are three ways to move the token from cell 3 to cell 1 in one shift: using subtraction of y = 2, or using division by z = 2 or z = 3.
There are also two ways to move the token from cell 3 to cell 1 via cell 2: first subtract y = 1, and then either subtract y = 1 again or divide by z = 2.
Therefore, there are five ways in total.
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 loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 β€ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all.
You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations.
Input
The first line contains two integers n and k (1 β€ n β€ 105, 0 β€ k β€ 109) β the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero.
Output
In the single line print the result without spaces β the number after the k operations are fulfilled.
Examples
Input
7 4
4727447
Output
4427477
Input
4 2
4478
Output
4478
Note
In the first sample the number changes in the following sequence: 4727447 β 4427447 β 4427477 β 4427447 β 4427477.
In the second sample: 4478 β 4778 β 4478.
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.
Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm.
.#.#.#.#.
.#.#.#.#.#
.#.#.#.#.
.#.#.#.#.#
.#.#.#.#.
.#.#.#.#.#
Note that the top left corner should be drawn by '#'.
Constraints
* 1 β€ H β€ 300
* 1 β€ W β€ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the chessboard made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
2 2
1 1
0 0
Output
#.#.
.#.#
#.#.
#.#.#.
.#.#.#
#.#.#.
.#.#.#
#.#.#.
#.#
.#.
#.#
#.
.#
#
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.
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 β₯ p_2 β₯ ... β₯ p_n.
Help the jury distribute the gold, silver and bronze medals. Let their numbers be g, s and b, respectively. Here is a list of requirements from the rules, which all must be satisfied:
* for each of the three types of medals, at least one medal must be awarded (that is, g>0, s>0 and b>0);
* the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, g<s and g<b, but there are no requirements between s and b);
* each gold medalist must solve strictly more problems than any awarded with a silver medal;
* each silver medalist must solve strictly more problems than any awarded a bronze medal;
* each bronze medalist must solve strictly more problems than any participant not awarded a medal;
* the total number of medalists g+s+b should not exceed half of all participants (for example, if n=21, then you can award a maximum of 10 participants, and if n=26, then you can award a maximum of 13 participants).
The jury wants to reward with medals the total maximal number participants (i.e. to maximize g+s+b) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals.
Input
The first line of the input contains an integer t (1 β€ t β€ 10000) β the number of test cases in the input. Then t test cases follow.
The first line of a test case contains an integer n (1 β€ n β€ 4β
10^5) β the number of BeRC participants. The second line of a test case contains integers p_1, p_2, ..., p_n (0 β€ p_i β€ 10^6), where p_i is equal to the number of problems solved by the i-th participant from the final standings. The values p_i are sorted in non-increasing order, i.e. p_1 β₯ p_2 β₯ ... β₯ p_n.
The sum of n over all test cases in the input does not exceed 4β
10^5.
Output
Print t lines, the j-th line should contain the answer to the j-th test case.
The answer consists of three non-negative integers g, s, b.
* Print g=s=b=0 if there is no way to reward participants with medals so that all requirements from the statement are satisfied at the same time.
* Otherwise, print three positive numbers g, s, b β the possible number of gold, silver and bronze medals, respectively. The sum of g+s+b should be the maximum possible. If there are several answers, print any of them.
Example
Input
5
12
5 4 4 3 2 2 1 1 1 1 1 1
4
4 3 2 1
1
1000000
20
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
32
64 64 63 58 58 58 58 58 37 37 37 37 34 34 28 28 28 28 28 28 24 24 19 17 17 17 17 16 16 16 16 11
Output
1 2 3
0 0 0
0 0 0
2 5 3
2 6 6
Note
In the first test case, it is possible to reward 1 gold, 2 silver and 3 bronze medals. In this case, the participant solved 5 tasks will be rewarded with the gold medal, participants solved 4 tasks will be rewarded with silver medals, participants solved 2 or 3 tasks will be rewarded with bronze medals. Participants solved exactly 1 task won't be rewarded. It's easy to see, that in this case, all conditions are satisfied and it is possible to reward participants in this way. It is impossible to give more than 6 medals because the number of medals should not exceed half of the number of participants. The answer 1, 3, 2 is also correct in this test case.
In the second and third test cases, it is impossible to reward medals, because at least one medal of each type should be given, but the number of medals should not exceed half of the number of participants.
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 widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.
You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.
You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.
The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as <image>, where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.
The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.
Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.
Input
The first line contains a single integer n (1 β€ n β€ 15) β the number of words in Lesha's problem. The second line contains n space-separated words β the short description of the problem.
The third line contains a single integer m (1 β€ m β€ 10) β the number of problems in the Torcoder.com archive. Next m lines contain the descriptions of the problems as "k s1 s2 ... sk", where k (1 β€ k β€ 500000) is the number of words in the problem and si is a word of the problem description.
All words from all problem descriptions contain no more than 10 lowercase English letters. It is guaranteed that the total length of words in all problem descriptions does not exceed 500015.
Output
If Lesha's problem is brand new, print string "Brand new problem!" (without quotes).
Otherwise, on the first line print the index of the archive problem which resembles Lesha's problem most. If there are multiple such problems, print the one with the smallest index. On the second line print a string consisting of characters [:, character | repeated p times, and characters :], where p is the "similarity" between this problem and Lesha's one. The archive problems are numbered starting from one in the order in which they are given in the input.
Examples
Input
4
find the next palindrome
1
10 find the previous palindrome or print better luck next time
Output
1
[:||||||:]
Input
3
add two numbers
3
1 add
2 two two
3 numbers numbers numbers
Output
Brand new problem!
Input
4
these papers are formulas
3
6 what are these formulas and papers
5 papers are driving me crazy
4 crazy into the night
Output
1
[:||||:]
Input
3
add two decimals
5
4 please two decimals add
5 decimals want to be added
4 two add decimals add
4 add one two three
7 one plus two plus three equals six
Output
3
[:|||:]
Note
Let us remind you that the number of inversions is the number of pairs of words that follow in the permutation not in their original order. Thus, for example, if the original problem is "add two numbers", then permutation "numbers add two" contains two inversions β pairs of words "numbers" and "add", "numbers" and "two".
Sequence b1, b2, ..., bk is a subsequence of sequence a1, a2, ..., an if there exists such a set of indices 1 β€ i1 < i2 < ... < ik β€ n that aij = bj (in other words, if sequence b can be obtained from a by deleting some of its elements).
In the first test case the first problem contains the "find the palindrome next" permutation as a subsequence, in which the number of inversions equals 1 (words "palindrome" and "next").
In the second test case there is no problem that contains a permutation of words from Lesha's problem as a subsequence.
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.
Recently Chef bought a bunch of robot-waiters. And now he needs to know how much to pay for the electricity that robots use for their work. All waiters serve food from the kitchen (which is in the point (0, 0)) and carry it to some table (which is in some point (x, y)) in a shortest way. But this is a beta version of robots and they can only do the next moves: turn right and make a step forward or turn left and make a step forward. Initially they look in direction of X-axis. Your task is to calculate for each query the number of moves theyβll do to reach corresponding table.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. For each test case there is a sing line containing two space-separated integers - x and y.
------ Output ------
For each test case, output a single line containing number of moves that robot will make to reach point (x, y)
------ Constraints ------
$1 β€ T β€ 10^{5}$
$-10^{9} β€ x, y β€ 10^{9}$
Β
----- Sample Input 1 ------
2
3 3
3 4
----- Sample Output 1 ------
6
7
------ Explanation 0 ------
Example case 1. Sequence of moves would be LRLRLR
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.
Bob is travelling from one city to another. In his way, he sees many other cities pass by. What he does instead of learning the full names of the cities, he learns just the first character of the cities. For example, if he passes by "bhopal", he will just remember the 'b'.
Given the list of N cities that come in his way, print "YES" or "NO" depending on if he is able to remember all the cities distinctly or not.
Note: City name consists of small English alphabets only.
Input and Output:
First line contains T, the number of testcases. Each testcase consists of N, the number of cities. Next N lines contain the names of the cities.
For each testcase, print "YES" or "NO" (quotes for clarity).
Constraints:
1 β€ T β€ 100
1 β€ N β€ 1000
1 β€ Length of each city name β€ 10
SAMPLE INPUT
2
2
bhopal
delhi
3
bhopal
delhi
dehradun
SAMPLE OUTPUT
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.
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns β from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (x_{k}, y_{k}).
The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. [Image]
Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!
-----Input-----
The first line of the input contains fix integers n, m, x, y, z, p (1 β€ n, m β€ 10^9;Β 0 β€ x, y, z β€ 10^9;Β 1 β€ p β€ 10^5).
Each of the following p lines contains two integers x_{k}, y_{k} (1 β€ x_{k} β€ n;Β 1 β€ y_{k} β€ m) β the initial coordinates of the k-th candy. Two candies can lie on the same cell.
-----Output-----
For each of the p candies, print on a single line its space-separated new coordinates.
-----Examples-----
Input
3 3 3 1 1 9
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
1 3
1 2
1 1
2 3
2 2
2 1
3 3
3 2
3 1
-----Note-----
Just for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:
QWER REWQ
ASDF -> FDSA
ZXCV VCXZ
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.
Shohag has an integer sequence $a_1, a_2, \ldots, a_n$. He can perform the following operation any number of times (possibly, zero):
Select any positive integer $k$ (it can be different in different operations).
Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert $k$ into the sequence at this position.
This way, the sequence $a$ changes, and the next operation is performed on this changed sequence.
For example, if $a=[3,3,4]$ and he selects $k = 2$, then after the operation he can obtain one of the sequences $[\underline{2},3,3,4]$, $[3,\underline{2},3,4]$, $[3,3,\underline{2},4]$, or $[3,3,4,\underline{2}]$.
Shohag wants this sequence to satisfy the following condition: for each $1 \le i \le |a|$, $a_i \le i$. Here, $|a|$ denotes the size of $a$.
Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 200$) β the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 100$) β the initial length of the sequence.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) β the elements of the sequence.
-----Output-----
For each test case, print a single integer β the minimum number of operations needed to perform to achieve the goal mentioned in the statement.
-----Examples-----
Input
4
3
1 3 4
5
1 2 5 7 4
1
1
3
69 6969 696969
Output
1
3
0
696966
-----Note-----
In the first test case, we have to perform at least one operation, as $a_2=3>2$. We can perform the operation $[1, 3, 4] \rightarrow [1, \underline{2}, 3, 4]$ (the newly inserted element is underlined), now the condition is satisfied.
In the second test case, Shohag can perform the following operations:
$[1, 2, 5, 7, 4] \rightarrow [1, 2, \underline{3}, 5, 7, 4] \rightarrow [1, 2, 3, \underline{4}, 5, 7, 4] \rightarrow [1, 2, 3, 4, 5, \underline{3}, 7, 4]$.
In the third test case, the sequence already satisfies the condition.
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 rectangle grid. That grid's size is n Γ m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β a pair of integers (x, y) (0 β€ x β€ n, 0 β€ y β€ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 β€ x1 β€ x β€ x2 β€ n, 0 β€ y1 β€ y β€ y2 β€ m, <image>.
The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers.
<image>
If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.
Input
The first line contains six integers n, m, x, y, a, b (1 β€ n, m β€ 109, 0 β€ x β€ n, 0 β€ y β€ m, 1 β€ a β€ n, 1 β€ b β€ m).
Output
Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).
Examples
Input
9 9 5 5 2 1
Output
1 3 9 7
Input
100 100 52 50 46 56
Output
17 8 86 92
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 recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
`14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the OEIS)
Keith numbers were introduced by Mike Keith in 1987. They are computationally very challenging to find, with only about 100 known.
Implement the code to check if the given number is a Keith number. Return the number number of iteration needed to confirm it; otherwise return `false`.
**Note:** 1-digit numbers are **not** Keith numbers by definition
## Examples
```
n = 197 # --> [1, 9, 7]
# calculation iteration
1 + 9 + 7 = 17 # 1
9 + 7 + 17 = 33 # 2
7 + 17 + 33 = 57 # 3
17 + 33 + 57 = 107 # 4
33 + 57 + 107 = 197 # 5
```
As `197` is the same as the initial number, so it's a Keith number: return `5`
Another example:
```
n = 196
# calculation iteration
1 + 9 + 6 = 16 # 1
...
```
`196` is not a Keith number, so return `false`
Write your solution by modifying this code:
```python
def is_keith_number(n):
```
Your solution should implemented in the function "is_keith_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.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip 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.
Find the volume of a cone whose radius and height are provided as parameters to the function `volume`. Use the value of PI provided by your language (for example: `Math.PI` in JS, `math.pi` in Python or `Math::PI` in Ruby) and round down the volume to an Interger.
If you complete this kata and there are no issues, please remember to give it a ready vote and a difficulty rating. :)
Write your solution by modifying this code:
```python
def volume(r,h):
```
Your solution should implemented in the function "volume". 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.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
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
Nathan O. Davis is a student at the department of integrated systems.
Today's agenda in the class is audio signal processing. Nathan was given a lot of homework out. One of the homework was to write a program to process an audio signal. He copied the given audio signal to his USB memory and brought it back to his home.
When he started his homework, he unfortunately dropped the USB memory to the floor. He checked the contents of the USB memory and found that the audio signal data got broken.
There are several characteristics in the audio signal that he copied.
* The audio signal is a sequence of $N$ samples.
* Each sample in the audio signal is numbered from $1$ to $N$ and represented as an integer value.
* Each value of the odd-numbered sample(s) is strictly smaller than the value(s) of its neighboring sample(s).
* Each value of the even-numbered sample(s) is strictly larger than the value(s) of its neighboring sample(s).
He got into a panic and asked you for a help. You tried to recover the audio signal from his USB memory but some samples of the audio signal are broken and could not be recovered. Fortunately, you found from the metadata that all the broken samples have the same integer value.
Your task is to write a program, which takes the broken audio signal extracted from his USB memory as its input, to detect whether the audio signal can be recovered uniquely.
Input
The input consists of multiple datasets. The form of each dataset is described below.
> $N$
> $a_{1}$ $a_{2}$ ... $a_{N}$
The first line of each dataset consists of an integer, $N (2 \le N \le 1{,}000)$. $N$ denotes the number of samples in the given audio signal. The second line of each dataset consists of $N$ values separated by spaces. The $i$-th value, $a_{i}$, is either a character `x` or an integer between $-10^9$ and $10^9$, inclusive. It represents the $i$-th sample of the broken audio signal. If $a_{i}$ is a character `x` , it denotes that $i$-th sample in the audio signal is broken. Otherwise it denotes the value of the $i$-th sample.
The end of input is indicated by a single $0$. This is not included in the datasets.
You may assume that the number of the datasets does not exceed $100$.
Output
For each dataset, output the value of the broken samples in one line if the original audio signal can be recovered uniquely. If there are multiple possible values, output `ambiguous`. If there are no possible values, output `none`.
Sample Input
5
1 x 2 4 x
2
x x
2
1 2
2
2 1
2
1000000000 x
4
x 2 1 x
0
Output for the Sample Input
3
none
ambiguous
none
ambiguous
none
Example
Input
5
1 x 2 4 x
2
x x
2
1 2
2
2 1
2
1000000000 x
4
x 2 1 x
0
Output
3
none
ambiguous
none
ambiguous
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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.