task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Title: Rational Resistance
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance *R*0<==<=1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor; 1. an element and one resistor plugged in sequence; 1. an element and one resistor plugged in parallel.
With the consecutive connection the resistance of the new element equals *R*<==<=*R**e*<=+<=*R*0. With the parallel connection the resistance of the new element equals . In this case *R**e* equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction . Determine the smallest possible number of resistors he needs to make such an element.
Input Specification:
The single input line contains two space-separated integers *a* and *b* (1<=β€<=*a*,<=*b*<=β€<=1018). It is guaranteed that the fraction is irreducible. It is guaranteed that a solution always exists.
Output Specification:
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Demo Input:
['1 1\n', '3 2\n', '199 200\n']
Demo Output:
['1\n', '3\n', '200\n']
Note:
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5305da389756aab6423d918a08ced468f05604df.png" style="max-width: 100.0%;max-height: 100.0%;"/>. We cannot make this element using two resistors. | 1,500 |
Title: Moore's Law
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.
Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.
You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.
Input Specification:
The only line of the input contains a pair of integers *n* (1000<=β€<=*n*<=β€<=10Β 000) and *t* (0<=β€<=*t*<=β€<=2Β 000Β 000Β 000)Β β the number of transistors in the initial time and the number of seconds passed since the initial time.
Output Specification:
Output one number β the estimate of the number of transistors in a dence integrated circuit in *t* seconds since the initial time. The relative error of your answer should not be greater than 10<=-<=6.
Demo Input:
['1000 1000000\n']
Demo Output:
['1011.060722383550382782399454922040\n']
Note:
none | 1,501 |
Title: Contact
Time Limit: 3 seconds
Memory Limit: 256 megabytes
Problem Description:
Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input Specification:
Each of 4 lines will contain 6 integers *x*1 *y*1 *x*2 *y*2 *x*3 *y*3 (0<=β€<=*x*1,<=*y*1,<=*x*2,<=*y*2,<=*x*3,<=*y*3<=β€<=20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output Specification:
First line should contain minimum number of columns enough to land all spaceships.
Demo Input:
['0 0 1 0 1 2\n0 0 0 2 2 2\n0 0 3 0 1 2\n0 0 3 0 2 2\n', '0 0 0 1 1 1\n0 0 0 2 2 2\n0 0 0 5 5 5\n0 0 0 17 17 17\n']
Demo Output:
['4\n', '9\n']
Note:
In the first test case columns can be put in these points: (0,β0),β(1,β0),β(3,β0),β(1,β2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0,β0),β(0,β1),β(1,β0),β(0,β2),β(2,β0),β(0,β5),β(5,β0),β(0,β17),β(17,β0). It is impossible to use less than 9 columns. | 1,502 |
Title: Sagheer and Nubian Market
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains *n* different items numbered from 1 to *n*. The *i*-th item has base cost *a**i* Egyptian pounds. If Sagheer buys *k* items with indices *x*1,<=*x*2,<=...,<=*x**k*, then the cost of item *x**j* is *a**x**j*<=+<=*x**j*Β·*k* for 1<=β€<=*j*<=β€<=*k*. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor *k*.
Sagheer wants to buy as many souvenirs as possible without paying more than *S* Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?
Input Specification:
The first line contains two integers *n* and *S* (1<=β€<=*n*<=β€<=105 and 1<=β€<=*S*<=β€<=109)Β β the number of souvenirs in the market and Sagheer's budget.
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=105)Β β the base costs of the souvenirs.
Output Specification:
On a single line, print two integers *k*, *T*Β β the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these *k* souvenirs.
Demo Input:
['3 11\n2 3 5\n', '4 100\n1 2 5 6\n', '1 7\n7\n']
Demo Output:
['2 11\n', '4 54\n', '0 0\n']
Note:
In the first example, he cannot take the three items because they will cost him [5,β9,β14] with total cost 28. If he decides to take only two items, then the costs will be [4,β7,β11]. So he can afford the first and second items.
In the second example, he can buy all items as they will cost him [5,β10,β17,β22].
In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. | 1,503 |
Title: Find Color
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Not so long ago as a result of combat operations the main Berland place of interest β the magic clock β was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin corresponds to the clock center. The clock was painted two colors as is shown in the picture:
The picture shows only the central part of the clock. This coloring naturally extends to infinity.
The balls can be taken to be points on the plane. Your task is to find the color of the area, damaged by the given ball.
All the points located on the border of one of the areas have to be considered painted black.
Input Specification:
The first and single line contains two integers *x* and *y* β the coordinates of the hole made in the clock by the ball. Each of the numbers *x* and *y* has an absolute value that does not exceed 1000.
Output Specification:
Find the required color.
All the points between which and the origin of coordinates the distance is integral-value are painted black.
Demo Input:
['-2 1\n', '2 1\n', '4 3\n']
Demo Output:
['white\n', 'black\n', 'black\n']
Note:
none | 1,504 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.
In this game there are *n* objects numbered from 1 to *n* arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario.
Each one of them has a set of numbers between 1 and *n*<=-<=1 (inclusive). Rick's set is *s*1 with *k*1 elements and Morty's is *s*2 with *k*2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like *x* from his set and the monster will move to his *x*-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.
Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.
Input Specification:
The first line of input contains a single integer *n* (2<=β€<=*n*<=β€<=7000) β number of objects in game.
The second line contains integer *k*1 followed by *k*1 distinct integers *s*1,<=1,<=*s*1,<=2,<=...,<=*s*1,<=*k*1 β Rick's set.
The third line contains integer *k*2 followed by *k*2 distinct integers *s*2,<=1,<=*s*2,<=2,<=...,<=*s*2,<=*k*2 β Morty's set
1<=β€<=*k**i*<=β€<=*n*<=-<=1 and 1<=β€<=*s**i*,<=1,<=*s**i*,<=2,<=...,<=*s**i*,<=*k**i*<=β€<=*n*<=-<=1 for 1<=β€<=*i*<=β€<=2.
Output Specification:
In the first line print *n*<=-<=1 words separated by spaces where *i*-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number *i*<=+<=1 he wins, "Lose" if he loses and "Loop" if the game will never end.
Similarly, in the second line print *n*<=-<=1 words separated by spaces where *i*-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number *i*<=+<=1 he wins, "Lose" if he loses and "Loop" if the game will never end.
Demo Input:
['5\n2 3 2\n3 1 2 3\n', '8\n4 6 2 3 4\n2 3 6\n']
Demo Output:
['Lose Win Win Loop\nLoop Win Win Win\n', 'Win Win Win Win Win Win Win\nLose Win Lose Lose Win Lose Lose\n']
Note:
none | 1,505 |
Title: Ithea Plays With Chtholly
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This is an interactive problem. Refer to the Interaction section below for better understanding.
Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.
Initially, Ithea puts *n* clear sheets of paper in a line. They are numbered from 1 to *n* from left to right.
This game will go on for *m* rounds. In each round, Ithea will give Chtholly an integer between 1 and *c*, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).
Chtholly wins if, at any time, all the sheets are filled with a number and the *n* numbers are in non-decreasing order looking from left to right from sheet 1 to sheet *n*, and if after *m* rounds she still doesn't win, she loses the game.
Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.
Input Specification:
The first line contains 3 integers *n*,<=*m* and *c* (, means rounded up)Β β the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process.
Output Specification:
none
Demo Input:
['2 4 4\n2\n1\n3\n']
Demo Output:
['1\n2\n2\n']
Note:
In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game.
Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round.
The input format for hacking:
- The first line contains 3 integers *n*,β*m* and *c*; - The following *m* lines each contains an integer between 1 and *c*, indicating the number given to Chtholly in each round. | 1,506 |
Title: Ship's Shortest Path
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.
And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.
You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.
But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.
You can move your ship on the island edge, and it will be considered moving in the sea.
Now you have a sea map, and you have to decide what is the minimum cost for your trip.
Your starting point is (*xStart*, *yStart*), and the end point is (*xEnd*, *yEnd*), both points will be different.
The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
Input Specification:
The first line contains 4 integers, *xStart*, *yStart*, *xEnd* and *yEnd* (<=-<=100<=β€<=*xStart*,<=*yStart*,<=*xEnd*,<=*yEnd*<=β€<=100). The second line contains an integer *n*, which is the number of points in the polygon (3<=β€<=*n*<=β€<=30), followed by a line containing *n* pairs of integers *x* and *y*, which are the coordinates of the points (<=-<=100<=β€<=*x*,<=*y*<=β€<=100), the polygon points will be distinct.
Output Specification:
Print one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10<=-<=6.
Demo Input:
['1 7 6 7\n4\n4 2 4 12 3 12 3 2\n', '-1 0 2 0\n4\n0 0 1 0 1 1 0 1\n']
Demo Output:
['6.000000000\n', '3.000000000\n']
Note:
none | 1,507 |
Title: Flying Saucer Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).
The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one β to the 1-st and the 3-rd ones, the 3-rd one β only to the 2-nd one. The transitions are possible only between the adjacent sections.
The spacecraft team consists of *n* aliens. Each of them is given a rank β an integer from 1 to *n*. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section *a* to section *b* only if it is senior in rank to all aliens who are in the segments *a* and *b* (besides, the segments *a* and *b* are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.
Alien *A* is senior in rank to alien *B*, if the number indicating rank *A*, is more than the corresponding number for *B*.
At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.
Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo *m*.
Input Specification:
The first line contains two space-separated integers: *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=109) β the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly.
Output Specification:
Print a single number β the answer to the problem modulo *m*.
Demo Input:
['1 10\n', '3 8\n']
Demo Output:
['2\n', '2\n']
Note:
In the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes.
To briefly describe the movements in the second sample we will use value <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4c7c8e716067e9c6251e8ca82a4ca7fde74fbacb.png" style="max-width: 100.0%;max-height: 100.0%;"/>, which would correspond to an alien with rank *i* moving from the segment in which it is at the moment, to the segment number *j*. Using these values, we will describe the movements between the segments in the second sample: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d4fd9e68a9c6a277942eb188291d6d2744ea21d3.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b73a9870e1b41a5e048c3ab3e3fd4b92c336c9ec.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/49b1ffd4dcd2e0da0acec04559e0c3efc7854b07.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ef8b3f32ee76c86f57fa63f7251fa290642f17f8.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/954e2f634474269f53df1edbf2e7b214d8a2611c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/be5f59dacfc6f7ded42f8f260c7b7aedf17ec1f0.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d4fd9e68a9c6a277942eb188291d6d2744ea21d3.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7668900e59f9bc3ccc78b0a77dca322fcb02fa04.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1adb8798904e42944c35bd49feff02db6c3ea10b.png" style="max-width: 100.0%;max-height: 100.0%;"/>; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2. | 1,508 |
Title: Fafa and Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Fafa has an array *A* of *n* positive integers, the function *f*(*A*) is defined as . He wants to do *q* queries of two types:
- 1<=*l*<=*r*<=*x* β find the maximum possible value of *f*(*A*), if *x* is to be added to one element in the range [*l*,<=<=*r*]. You can choose to which element to add *x*. - 2<=*l*<=*r*<=*x* β increase all the elements in the range [*l*,<=<=*r*] by value *x*.
Note that queries of type 1 don't affect the array elements.
Input Specification:
The first line contains one integer *n* (3<=β€<=*n*<=β€<=105) β the length of the array.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (0<=<<=*a**i*<=β€<=109) β the array elements.
The third line contains an integer *q* (1<=β€<=*q*<=β€<=105) β the number of queries.
Then *q* lines follow, line *i* describes the *i*-th query and contains four integers *t**i*<=*l**i*<=*r**i*<=*x**i* .
It is guaranteed that at least one of the queries is of type 1.
Output Specification:
For each query of type 1, print the answer to the query.
Demo Input:
['5\n1 1 1 1 1\n5\n1 2 4 1\n2 2 3 1\n2 4 4 2\n2 3 4 1\n1 3 3 2\n', '5\n1 2 3 4 5\n4\n1 2 4 2\n2 2 4 1\n2 3 4 1\n1 2 4 2\n']
Demo Output:
['2\n8\n', '6\n10\n']
Note:
none | 1,509 |
Title: Cycles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly *k* cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices *a*, *b* and *c*, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input Specification:
A single line contains an integer *k* (1<=β€<=*k*<=β€<=105) β the number of cycles of length 3 in the required graph.
Output Specification:
In the first line print integer *n* (3<=β€<=*n*<=β€<=100) β the number of vertices in the found graph. In each of next *n* lines print *n* characters "0" and "1": the *i*-th character of the *j*-th line should equal "0", if vertices *i* and *j* do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the *i*-th character of the *j*-th line must equal the *j*-th character of the *i*-th line. The graph shouldn't contain self-loops, so the *i*-th character of the *i*-th line must equal "0" for all *i*.
Demo Input:
['1\n', '10\n']
Demo Output:
['3\n011\n101\n110\n', '5\n01111\n10111\n11011\n11101\n11110\n']
Note:
none | 1,510 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*.
Prefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end.
Asterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened.
You know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend.
Input Specification:
You are given the string *s* whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output Specification:
Print the string *t*. If a suitable *t* string does not exist, then print "Just a legend" without the quotes.
Demo Input:
['fixprefixsuffix\n', 'abcdabc\n']
Demo Output:
['fix', 'Just a legend']
Note:
none | 1,511 |
Title: Kalevitch and Chess
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.
As before, the chessboard is a square-checkered board with the squares arranged in a 8<=Γ<=8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.
Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.
It goes without saying that in such business one should economize on everything β for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
Input Specification:
The input file contains 8 lines, each of the lines contains 8 characters. The given matrix describes the client's requirements, W character stands for a white square, and B character β for a square painted black.
It is guaranteed that client's requirments can be fulfilled with a sequence of allowed strokes (vertical/column or horizontal/row).
Output Specification:
Output the only number β the minimum amount of rows and columns that Kalevitch has to paint on the white chessboard to meet the client's requirements.
Demo Input:
['WWWBWWBW\nBBBBBBBB\nWWWBWWBW\nWWWBWWBW\nWWWBWWBW\nWWWBWWBW\nWWWBWWBW\nWWWBWWBW\n', 'WWWWWWWW\nBBBBBBBB\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\n']
Demo Output:
['3\n', '1\n']
Note:
none | 1,512 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Treeland is a country in which there are *n* towns connected by *n*<=-<=1 two-way road such that it's possible to get from any town to any other town.
In Treeland there are 2*k* universities which are located in different towns.
Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done!
To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in *k* pairs should be as large as possible.
Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1.
Input Specification:
The first line of the input contains two integers *n* and *k* (2<=β€<=*n*<=β€<=200<=000, 1<=β€<=*k*<=β€<=*n*<=/<=2)Β β the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to *n*.
The second line contains 2*k* distinct integers *u*1,<=*u*2,<=...,<=*u*2*k* (1<=β€<=*u**i*<=β€<=*n*)Β β indices of towns in which universities are located.
The next *n*<=-<=1 line contains the description of roads. Each line contains the pair of integers *x**j* and *y**j* (1<=β€<=*x**j*,<=*y**j*<=β€<=*n*), which means that the *j*-th road connects towns *x**j* and *y**j*. All of them are two-way roads. You can move from any town to any other using only these roads.
Output Specification:
Print the maximum possible sum of distances in the division of universities into *k* pairs.
Demo Input:
['7 2\n1 5 6 2\n1 3\n3 2\n4 5\n3 7\n4 3\n4 6\n', '9 3\n3 2 1 6 5 9\n8 9\n3 2\n2 7\n3 4\n7 6\n4 5\n2 1\n2 8\n']
Demo Output:
['6\n', '9\n']
Note:
The figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example. | 1,513 |
Title: Can Bash Save the Day?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Whoa! You did a great job helping Team Rocket who managed to capture all the Pokemons sent by Bash. Meowth, part of Team Rocket, having already mastered the human language, now wants to become a master in programming as well. He agrees to free the Pokemons if Bash can answer his questions.
Initially, Meowth gives Bash a weighted tree containing *n* nodes and a sequence *a*1,<=*a*2...,<=*a**n* which is a permutation of 1,<=2,<=...,<=*n*. Now, Mewoth makes *q* queries of one of the following forms:
- 1 l r v: meaning Bash should report , where *dist*(*a*,<=*b*) is the length of the shortest path from node *a* to node *b* in the given tree. - 2 x: meaning Bash should swap *a**x* and *a**x*<=+<=1 in the given sequence. This new sequence is used for later queries.
Help Bash to answer the questions!
Input Specification:
The first line contains two integers *n* and *q* (1<=β€<=*n*<=β€<=2Β·105, 1<=β€<=*q*<=β€<=2Β·105)Β β the number of nodes in the tree and the number of queries, respectively.
The next line contains *n* space-separated integersΒ β the sequence *a*1,<=*a*2,<=...,<=*a**n* which is a permutation of 1,<=2,<=...,<=*n*.
Each of the next *n*<=-<=1 lines contain three space-separated integers *u*, *v*, and *w* denoting that there exists an undirected edge between node *u* and node *v* of weight *w*, (1<=β€<=*u*,<=*v*<=β€<=*n*, *u*<=β <=*v*, 1<=β€<=*w*<=β€<=106). It is guaranteed that the given graph is a tree.
Each query consists of two lines. First line contains single integer *t*, indicating the type of the query. Next line contains the description of the query:
- t = 1: Second line contains three integers *a*, *b* and *c* (1<=β€<=*a*,<=*b*,<=*c*<=<<=230) using which *l*, *r* and *v* can be generated using the formula given below: , - , - . - .
The *ans**i* is the answer for the *i*-th query, assume that *ans*0<==<=0. If the *i*-th query is of type 2 then *ans**i* = *ans**i*<=-<=1. It is guaranteed that:
- for each query of type 1: 1<=β€<=*l*<=β€<=*r*<=β€<=*n*, 1<=β€<=*v*<=β€<=*n*, - for each query of type 2: 1<=β€<=*x*<=β€<=*n*<=-<=1.
The operation means bitwise exclusive OR.
Output Specification:
For each query of type 1, output a single integer in a separate line, denoting the answer to the query.
Demo Input:
['5 5\n4 5 1 3 2\n4 2 4\n1 3 9\n4 1 4\n4 5 2\n1\n1 5 4\n1\n22 20 20\n2\n38\n2\n39\n1\n36 38 38\n']
Demo Output:
['23\n37\n28\n']
Note:
In the sample, the actual queries are the following:
- 1 1 5 4 - 1 1 3 3 - 2 3 - 2 2 - 1 1 3 3 | 1,514 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Consider a sequence [*a*1,<=*a*2,<=... ,<=*a**n*]. Define its prefix product sequence .
Now given *n*, find a permutation of [1,<=2,<=...,<=*n*], such that its prefix product sequence is a permutation of [0,<=1,<=...,<=*n*<=-<=1].
Input Specification:
The only input line contains an integer *n* (1<=β€<=*n*<=β€<=105).
Output Specification:
In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists.
If any solution exists, you should output *n* more lines. *i*-th line contains only an integer *a**i*. The elements of the sequence should be different positive integers no larger than *n*.
If there are multiple solutions, you are allowed to print any of them.
Demo Input:
['7\n', '6\n']
Demo Output:
['YES\n1\n4\n3\n6\n5\n2\n7\n', 'NO\n']
Note:
For the second sample, there are no valid sequences. | 1,515 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
DZY has a sequence *a*, consisting of *n* integers.
We'll call a sequence *a**i*,<=*a**i*<=+<=1,<=...,<=*a**j* (1<=β€<=*i*<=β€<=*j*<=β€<=*n*) a subsegment of the sequence *a*. The value (*j*<=-<=*i*<=+<=1) denotes the length of the subsegment.
Your task is to find the longest subsegment of *a*, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.
You only need to output the length of the subsegment you find.
Input Specification:
The first line contains integer *n*Β (1<=β€<=*n*<=β€<=105). The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n*Β (1<=β€<=*a**i*<=β€<=109).
Output Specification:
In a single line print the answer to the problem β the maximum length of the required subsegment.
Demo Input:
['6\n7 2 3 1 5 6\n']
Demo Output:
['5\n']
Note:
You can choose subsegment *a*<sub class="lower-index">2</sub>,β*a*<sub class="lower-index">3</sub>,β*a*<sub class="lower-index">4</sub>,β*a*<sub class="lower-index">5</sub>,β*a*<sub class="lower-index">6</sub> and change its 3rd element (that is *a*<sub class="lower-index">4</sub>) to 4. | 1,516 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are *n* players (including Limak himself) and right now all of them have bids on the table. *i*-th of them has bid with size *a**i* dollars.
Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
Input Specification:
First line of input contains an integer *n* (2<=β€<=*n*<=β€<=105), the number of players.
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109) β the bids of players.
Output Specification:
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
Demo Input:
['4\n75 150 75 50\n', '3\n100 150 250\n']
Demo Output:
['Yes\n', 'No\n']
Note:
In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.
It can be shown that in the second sample test there is no way to make all bids equal. | 1,517 |
Title: Bear and Chase
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bearland has *n* cities, numbered 1 through *n*. There are *m* bidirectional roads. The *i*-th road connects two distinct cities *a**i* and *b**i*. No two roads connect the same pair of cities. It's possible to get from any city to any other city (using one or more roads).
The distance between cities *a* and *b* is defined as the minimum number of roads used to travel between *a* and *b*.
Limak is a grizzly bear. He is a criminal and your task is to catch him, or at least to try to catch him. You have only two days (today and tomorrow) and after that Limak is going to hide forever.
Your main weapon is BCD (Bear Criminal Detector). Where you are in some city, you can use BCD and it tells you the distance between you and a city where Limak currently is. Unfortunately, BCD can be used only once a day.
You don't know much about Limak's current location. You assume that he is in one of *n* cities, chosen uniformly at random (each city with probability ). You decided for the following plan:
1. Choose one city and use BCD there. After using BCD you can try to catch Limak (but maybe it isn't a good idea). In this case you choose one city and check it. You win if Limak is there. Otherwise, Limak becomes more careful and you will never catch him (you loose). 1. Wait 24 hours to use BCD again. You know that Limak will change his location during that time. In detail, he will choose uniformly at random one of roads from his initial city, and he will use the chosen road, going to some other city. 1. Tomorrow, you will again choose one city and use BCD there. 1. Finally, you will try to catch Limak. You will choose one city and check it. You will win if Limak is there, and loose otherwise.
Each time when you choose one of cities, you can choose any of *n* cities. Let's say it isn't a problem for you to quickly get somewhere.
What is the probability of finding Limak, if you behave optimally?
Input Specification:
The first line of the input contains two integers *n* and *m* (2<=β€<=*n*<=β€<=400, )Β β the number of cities and the number of roads, respectively.
Then, *m* lines follow. The *i*-th of them contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*, *a**i*<=β <=*b**i*)Β β cities connected by the *i*-th road.
No two roads connect the same pair of cities. It's possible to get from any city to any other city.
Output Specification:
Print one real numberΒ β the probability of finding Limak, if you behave optimally. Your answer will be considered correct if its absolute error does not exceed 10<=-<=6.
Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct if |*a*<=-<=*b*|<=β€<=10<=-<=6.
Demo Input:
['3 3\n1 2\n1 3\n2 3\n', '5 4\n1 2\n3 1\n5 1\n1 4\n', '4 4\n1 2\n1 3\n2 3\n1 4\n', '5 5\n1 2\n2 3\n3 4\n4 5\n1 5\n']
Demo Output:
['0.833333333333\n', '1.000000000000\n', '0.916666666667\n', '0.900000000000\n']
Note:
In the first sample test, there are three cities and there is a road between every pair of cities. Let's analyze one of optimal scenarios.
1. Use BCD in city 1. <li> With probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/64c94d13eeb330b494061e86538db66574ad0f7d.png" style="max-width: 100.0%;max-height: 100.0%;"/> Limak is in this city and BCD tells you that the distance is 0. You should try to catch him now and you win for sure. 1. With probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/14b21b617fcd2e25700376368355f7bbf975d8de.png" style="max-width: 100.0%;max-height: 100.0%;"/> the distance is 1 because Limak is in city 2 or city 3. In this case you should wait for the second day. </li>1. You wait and Limak moves to some other city. <li> There is probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/45372faa18afd6691c4e5aa94c7b5edc43a23007.png" style="max-width: 100.0%;max-height: 100.0%;"/> that Limak was in city 2 and then went to city 3. 1. <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/45372faa18afd6691c4e5aa94c7b5edc43a23007.png" style="max-width: 100.0%;max-height: 100.0%;"/> that he went from 2 to 1. 1. <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/45372faa18afd6691c4e5aa94c7b5edc43a23007.png" style="max-width: 100.0%;max-height: 100.0%;"/> that he went from 3 to 2. 1. <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/45372faa18afd6691c4e5aa94c7b5edc43a23007.png" style="max-width: 100.0%;max-height: 100.0%;"/> that he went from 3 to 1. </li>1. Use BCD again in city 1 (though it's allowed to use it in some other city). <li> If the distance is 0 then you're sure Limak is in this city (you win). 1. If the distance is 1 then Limak is in city 2 or city 3. Then you should guess that he is in city 2 (guessing city 3 would be fine too). </li> - There is probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/45372faa18afd6691c4e5aa94c7b5edc43a23007.png" style="max-width: 100.0%;max-height: 100.0%;"/> that Limak was in city 2 and then went to city 3. - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/45372faa18afd6691c4e5aa94c7b5edc43a23007.png" style="max-width: 100.0%;max-height: 100.0%;"/> that he went from 2 to 1. - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/45372faa18afd6691c4e5aa94c7b5edc43a23007.png" style="max-width: 100.0%;max-height: 100.0%;"/> that he went from 3 to 2. - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/45372faa18afd6691c4e5aa94c7b5edc43a23007.png" style="max-width: 100.0%;max-height: 100.0%;"/> that he went from 3 to 1.
You loose only if Limak was in city 2 first and then he moved to city 3. The probability of loosing is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/55bd5cf64609940bba840be4d13d882b3b49c511.png" style="max-width: 100.0%;max-height: 100.0%;"/>. The answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/56d7c14b8db6605aa95b947bca89a66828b49171.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | 1,518 |
Title: Tree and Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
User ainta likes trees. This time he is going to make an undirected tree with *n* vertices numbered by integers from 1 to *n*. The tree is weighted, so each edge of the tree will have some integer weight.
Also he has an array *t*: *t*[1],<=*t*[2],<=...,<=*t*[*n*]. At first all the elements of the array are initialized to 0. Then for each edge connecting vertices *u* and *v* (*u*<=<<=*v*) of the tree with weight *c*, ainta adds value *c* to the elements *t*[*u*],<=*t*[*u*<=+<=1],<=...,<=*t*[*v*<=-<=1],<=*t*[*v*] of array *t*.
Let's assume that *d*(*u*,<=*v*) is the total weight of edges on the shortest path between vertex *u* and vertex *v*. User ainta calls a pair of integers *x*,<=*y* (1<=β€<=*x*<=<<=*y*<=β€<=*n*) good if and only if *d*(*x*,<=*y*)<==<=*t*[*x*]<=+<=*t*[*x*<=+<=1]<=+<=...<=+<=*t*[*y*<=-<=1]<=+<=*t*[*y*].
User ainta wants to make at least good pairs, but he couldn't make a proper tree. Help ainta to find such a tree.
Input Specification:
The first line contains a single integer *n* (5<=β€<=*n*<=β€<=105).
Output Specification:
Print *n*<=-<=1 lines containing the description of the edges. The *i*-th line should contain three space-separated integers *u**i*,<=*v**i*,<=*c**i* (1<=β€<=*u**i*<=<<=*v**i*<=β€<=*n*;Β 1<=β€<=*c**i*<=β€<=105) β two vertices connected by the edge, and the weight of the edge.
Next print lines containing the good pairs. The *k*-th line should contain two space-separated integers *x**k* and *y**k* (1<=β€<=*x**k*<=<<=*y**k*<=β€<=*n*). Of course, *x**k*,<=*y**k* must be a good pair. All pairs should be distinct β that is, for all *j*,<=*k* , *x**j*<=β <=*x**k* or *y**j*<=β <=*y**k* must be satisfied.
If there are many correct solutions, print any of them.
Demo Input:
['7']
Demo Output:
['1 4 1\n1 2 2\n2 3 5\n3 5 3\n2 6 2\n6 7 3\n4 5\n5 6\n5 7']
Note:
β*x*β is the largest integer not greater than *x*.
You can find the definition of a tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory)
You can also find the definition of the shortest path by the following link: http://en.wikipedia.org/wiki/Shortest_path_problem
The tree and the array *t* in the sample output look like this: | 1,519 |
Title: Strange town
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Volodya has recently visited a very odd town. There are *N* tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour β a cycle which visits every attraction exactly once β the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.
Input Specification:
Input contains just one natural number (3<=β€<=*N*<=β€<=20) β the number of town attractions.
Output Specification:
Output should contain *N* rows containing *N* positive integer numbers each β the adjacency matrix of the prices graph (thus, *j*-th number in *i*-th row should be equal to the price of the road between the *j*-th and the *i*-th attraction). Diagonal numbers should be equal to zero. All numbers should not be greater than 1000. All prices should be positive and pairwise distinct. If there are several solutions, output any of them.
Demo Input:
['3\n']
Demo Output:
['0 3 4 \n3 0 5 \n4 5 0 \n']
Note:
none | 1,520 |
Title: The Child and Toy
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of *n* parts and *m* ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part *i* as *v**i*. The child spend *v**f*1<=+<=*v**f*2<=+<=...<=+<=*v**f**k* energy for removing part *i* where *f*1,<=*f*2,<=...,<=*f**k* are the parts that are directly connected to the *i*-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all *n* parts.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*<=β€<=1000; 0<=β€<=*m*<=β€<=2000). The second line contains *n* integers: *v*1,<=*v*2,<=...,<=*v**n* (0<=β€<=*v**i*<=β€<=105). Then followed *m* lines, each line contains two integers *x**i* and *y**i*, representing a rope from part *x**i* to part *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=*n*;Β *x**i*<=β <=*y**i*).
Consider all the parts are numbered from 1 to *n*.
Output Specification:
Output the minimum total energy the child should spend to remove all *n* parts of the toy.
Demo Input:
['4 3\n10 20 30 40\n1 4\n1 2\n2 3\n', '4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4\n', '7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4\n']
Demo Output:
['40\n', '400\n', '160\n']
Note:
One of the optimal sequence of actions in the first sample is:
- First, remove part 3, cost of the action is 20. - Then, remove part 2, cost of the action is 10. - Next, remove part 4, cost of the action is 10. - At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20β+β10β+β10β+β0β=β40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts. | 1,521 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Consider a regular Codeforces round consisting of three problems that uses dynamic scoring.
You are given an almost final scoreboard. For each participant (including yourself), the time of the accepted submission for each of the problems is given. Also, for each solution you already know whether you are able to hack it or not. The only changes in the scoreboard that will happen before the end of the round are your challenges.
What is the best place you may take at the end?
More formally, *n* people are participating (including yourself). For any problem, if it was solved by exactly *k* people at the end of the round, the maximum score for this problem is defined as:
1. If *n*<=<<=2*k*<=β€<=2*n*, then the maximum possible score is 500; 1. If *n*<=<<=4*k*<=β€<=2*n*, then the maximum possible score is 1000; 1. If *n*<=<<=8*k*<=β€<=2*n*, then the maximum possible score is 1500; 1. If *n*<=<<=16*k*<=β€<=2*n*, then the maximum possible score is 2000; 1. If *n*<=<<=32*k*<=β€<=2*n*, then the maximum possible score is 2500; 1. If 32*k*<=β€<=*n*, then the maximum possible score is 3000.
Let the maximum possible score for some problem be equal to *s*. Then a contestant who didn't manage to get it accepted (or his solution was hacked) earns 0 points for this problem. If he got the the solution accepted *t* minutes after the beginning of the round (and his solution wasn't hacked), he earns points for this problem.
The overall score of a participant is equal to the sum of points he earns for each problem plus 100 points for each successful hack (only you make hacks).
The resulting place you get is equal to one plus the number of participants who's overall score is strictly greater than yours.
Input Specification:
The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=5000)Β β the number of participants. You are the participant number 1.
Each of the following *n* lines contains three integers *a**i*, *b**i* and *c**i*. Here *a**i*<==<=0 means that the participant number *i* didn't manage to accept first problem. If 1<=β€<=*a**i*<=β€<=120, then the participant number *i* got the first problem accepted *a**i* minutes after the start of the contest and you cannot hack this solution. Finally, <=-<=120<=β€<=*a**i*<=β€<=<=-<=1 means that the participant number *i* got the first problem accepted <=-<=*a**i* minutes after the start of the contest and you can hack this solution. Similarly, *b**i* and *c**i* provide the information regarding second and third problems in the same format.
It's guaranteed that integers *a*1, *b*1 and *c*1 are non-negative.
Output Specification:
Print the only integerΒ β the best place you can take at the end of the round.
Demo Input:
['4\n120 120 1\n61 61 120\n-61 61 120\n0 0 0\n', '4\n0 0 119\n-3 -17 -42\n0 7 0\n51 0 0\n']
Demo Output:
['1\n', '2\n']
Note:
Consider the first sample. If you do not hack any solutions, you will win the contest (scoreboard to the left). However, if you hack the solution of the first problem of the third participant (the only one you can hack), the maximum score for the first problem will change and you will finish second (scoreboard to the right). | 1,522 |
Title: Burning Midnight Oil
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day a highly important task was commissioned to Vasya β writing a program in a night. The program consists of *n* lines of code. Vasya is already exhausted, so he works like that: first he writes *v* lines of code, drinks a cup of tea, then he writes as much as lines, drinks another cup of tea, then he writes lines and so on: , , , ...
The expression is regarded as the integral part from dividing number *a* by number *b*.
The moment the current value equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished.
Vasya is wondering, what minimum allowable value *v* can take to let him write not less than *n* lines of code before he falls asleep.
Input Specification:
The input consists of two integers *n* and *k*, separated by spaces β the size of the program in lines and the productivity reduction coefficient, 1<=β€<=*n*<=β€<=109, 2<=β€<=*k*<=β€<=10.
Output Specification:
Print the only integer β the minimum value of *v* that lets Vasya write the program in one night.
Demo Input:
['7 2\n', '59 9\n']
Demo Output:
['4\n', '54\n']
Note:
In the first sample the answer is *v*β=β4. Vasya writes the code in the following portions: first 4 lines, then 2, then 1, and then Vasya falls asleep. Thus, he manages to write 4β+β2β+β1β=β7 lines in a night and complete the task.
In the second sample the answer is *v*β=β54. Vasya writes the code in the following portions: 54, 6. The total sum is 54β+β6β=β60, that's even more than *n*β=β59. | 1,523 |
Title: String Set Queries
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You should process *m* queries over a set *D* of strings. Each query is one of three kinds:
1. Add a string *s* to the set *D*. It is guaranteed that the string *s* was not added before. 1. Delete a string *s* from the set *D*. It is guaranteed that the string *s* is in the set *D*. 1. For the given string *s* find the number of occurrences of the strings from the set *D*. If some string *p* from *D* has several occurrences in *s* you should count all of them.
Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query of the third type. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
Input Specification:
The first line contains integer *m* (1<=β€<=*m*<=β€<=3Β·105) β the number of queries.
Each of the next *m* lines contains integer *t* (1<=β€<=*t*<=β€<=3) and nonempty string *s* β the kind of the query and the string to process. All strings consist of only lowercase English letters.
The sum of lengths of all strings in the input will not exceed 3Β·105.
Output Specification:
For each query of the third kind print the only integer *c* β the desired number of occurrences in the string *s*.
Demo Input:
['5\n1 abc\n3 abcabc\n2 abc\n1 aba\n3 abababc\n', '10\n1 abc\n1 bcd\n1 abcd\n3 abcd\n2 abcd\n3 abcd\n2 bcd\n3 abcd\n2 abc\n3 abcd\n']
Demo Output:
['2\n2\n', '3\n2\n1\n0\n']
Note:
none | 1,524 |
Title: Power Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Genos and Saitama went shopping for Christmas trees. However, a different type of tree caught their attention, the exalted Power Tree.
A Power Tree starts out as a single root vertex indexed 1. A Power Tree grows through a magical phenomenon known as an update. In an update, a single vertex is added to the tree as a child of some other vertex.
Every vertex in the tree (the root and all the added vertices) has some value *v**i* associated with it. The power of a vertex is defined as the strength of the multiset composed of the value associated with this vertex (*v**i*) and the powers of its direct children. The strength of a multiset is defined as the sum of all elements in the multiset multiplied by the number of elements in it. Or in other words for some multiset *S*:
Saitama knows the updates that will be performed on the tree, so he decided to test Genos by asking him queries about the tree during its growth cycle.
An update is of the form 1Β *p*Β *v*, and adds a new vertex with value *v* as a child of vertex *p*.
A query is of the form 2Β *u*, and asks for the power of vertex *u*.
Please help Genos respond to these queries modulo 109<=+<=7.
Input Specification:
The first line of the input contains two space separated integers *v*1 and *q* (1<=β€<=*v*1<=<<=109, 1<=β€<=*q*<=β€<=200<=000) β the value of vertex 1 and the total number of updates and queries respectively.
The next *q* lines contain the updates and queries. Each of them has one of the following forms:
- 1Β *p**i*Β *v**i*, if these line describes an update. The index of the added vertex is equal to the smallest positive integer not yet used as an index in the tree. It is guaranteed that *p**i* is some already existing vertex and 1<=β€<=*v**i*<=<<=109. - 2Β *u**i*, if these line describes a query. It is guaranteed *u**i* will exist in the tree.
It is guaranteed that the input will contain at least one query.
Output Specification:
For each query, print out the power of the given vertex modulo 109<=+<=7.
Demo Input:
['2 5\n1 1 3\n1 2 5\n1 3 7\n1 4 11\n2 1\n', '5 5\n1 1 4\n1 2 3\n2 2\n1 2 7\n2 1\n']
Demo Output:
['344\n', '14\n94\n']
Note:
For the first sample case, after all the updates the graph will have vertices labelled in the following manner: 1 β 2 β 3 β 4 β 5
These vertices will have corresponding values: 2 β 3 β 5 β 7 β 11
And corresponding powers: 344 β 170 β 82 β 36 β 11 | 1,525 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence $a_1, \ldots, a_n$. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence $b_1, \ldots, b_n$ using the following rules:
- $b_1 = a_1$;- $b_i = a_i \oplus a_{i - 1}$ for all $i$ from 2 to $n$, where $x \oplus y$ is the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of $x$ and $y$.
It is easy to see that the original sequence can be obtained using the rule $a_i = b_1 \oplus \ldots \oplus b_i$.
However, some time later Vitya discovered that the integers $b_i$ in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers $b_i$ so that the sequence $a_i = b_1 \oplus \ldots \oplus b_i$ is strictly increasing. Help him find such a permutation or determine that it is impossible.
Input Specification:
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$).
The second line contains $n$ integers $b_1, \ldots, b_n$ ($1 \leq b_i < 2^{60}$).
Output Specification:
If there are no valid permutations, print a single line containing "No".
Otherwise in the first line print the word "Yes", and in the second line print integers $b'_1, \ldots, b'_n$Β β a valid permutation of integers $b_i$. The unordered multisets $\{b_1, \ldots, b_n\}$ and $\{b'_1, \ldots, b'_n\}$ should be equal, i.Β e. for each integer $x$ the number of occurrences of $x$ in the first multiset should be equal to the number of occurrences of $x$ in the second multiset. Apart from this, the sequence $a_i = b'_1 \oplus \ldots \oplus b'_i$ should be strictly increasing.
If there are multiple answers, print any of them.
Demo Input:
['3\n1 2 3\n', '6\n4 7 7 12 31 61\n']
Demo Output:
['No\n', 'Yes\n4 12 7 31 7 61 \n']
Note:
In the first example no permutation is valid.
In the second example the given answer lead to the sequence $a_1 = 4$, $a_2 = 8$, $a_3 = 15$, $a_4 = 16$, $a_5 = 23$, $a_6 = 42$. | 1,526 |
Title: Little Artem and 2-SAT
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Artem is a very smart programmer. He knows many different difficult algorithms. Recently he has mastered in 2-SAT one.
In computer science, 2-satisfiability (abbreviated as 2-SAT) is the special case of the problem of determining whether a conjunction (logical AND) of disjunctions (logical OR) have a solution, in which all disjunctions consist of no more than two arguments (variables). For the purpose of this problem we consider only 2-SAT formulas where each disjunction consists of exactly two arguments.
Consider the following 2-SAT problem as an example: . Note that there might be negations in 2-SAT formula (like for *x*1 and for *x*4).
Artem now tries to solve as many problems with 2-SAT as possible. He found a very interesting one, which he can not solve yet. Of course, he asks you to help him.
The problem is: given two 2-SAT formulas *f* and *g*, determine whether their sets of possible solutions are the same. Otherwise, find any variables assignment *x* such that *f*(*x*)<=β <=*g*(*x*).
Input Specification:
The first line of the input contains three integers *n*, *m*1 and *m*2 (1<=β€<=*n*<=β€<=1000, 1<=β€<=*m*1,<=*m*2<=β€<=*n*2)Β β the number of variables, the number of disjunctions in the first formula and the number of disjunctions in the second formula, respectively.
Next *m*1 lines contains the description of 2-SAT formula *f*. The description consists of exactly *m*1 pairs of integers *x**i* (<=-<=*n*<=β€<=*x**i*<=β€<=*n*,<=*x**i*<=β <=0) each on separate line, where *x**i*<=><=0 corresponds to the variable without negation, while *x**i*<=<<=0 corresponds to the variable with negation. Each pair gives a single disjunction. Next *m*2 lines contains formula *g* in the similar format.
Output Specification:
If both formulas share the same set of solutions, output a single word "SIMILAR" (without quotes). Otherwise output exactly *n* integers *x**i* ()Β β any set of values *x* such that *f*(*x*)<=β <=*g*(*x*).
Demo Input:
['2 1 1\n1 2\n1 2\n', '2 1 1\n1 2\n1 -2\n']
Demo Output:
['SIMILAR\n', '0 0 \n']
Note:
First sample has two equal formulas, so they are similar by definition.
In second sample if we compute first function with *x*<sub class="lower-index">1</sub>β=β0 and *x*<sub class="lower-index">2</sub>β=β0 we get the result 0, because <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/82cbca427149bc7516804c97b5963cbfddd08900.png" style="max-width: 100.0%;max-height: 100.0%;"/>. But the second formula is 1, because <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c8a53f3cfcb77e8a34515ff1420d44e5e2c3db0b.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | 1,527 |
Title: Palindromes in a Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a tree (a connected acyclic undirected graph) of *n* vertices. Vertices are numbered from 1 to *n* and each vertex is assigned a character from a to t.
A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.
For each vertex, output the number of palindromic paths passing through it.
Note: The path from vertex *u* to vertex *v* is considered to be the same as the path from vertex *v* to vertex *u*, and this path will be counted only once for each of the vertices it passes through.
Input Specification:
The first line contains an integer *n* (2<=β€<=*n*<=β€<=2Β·105) Β β the number of vertices in the tree.
The next *n*<=-<=1 lines each contain two integers *u* and *v* (1<=<=β€<=<=*u*,<=*v*<=<=β€<=<=*n*,<=*u*<=β <=*v*) denoting an edge connecting vertex *u* and vertex *v*. It is guaranteed that the given graph is a tree.
The next line contains a string consisting of *n* lowercase characters from a to t where the *i*-th (1<=β€<=*i*<=β€<=*n*) character is the label of vertex *i* in the tree.
Output Specification:
Print *n* integers in a single line, the *i*-th of which is the number of palindromic paths passing through vertex *i* in the tree.
Demo Input:
['5\n1 2\n2 3\n3 4\n3 5\nabcbb\n', '7\n6 2\n4 3\n3 7\n5 2\n7 2\n1 4\nafefdfs\n']
Demo Output:
['1 3 4 3 3 \n', '1 4 1 1 2 4 2 \n']
Note:
In the first sample case, the following paths are palindromic:
2β-β3β-β4
2β-β3β-β5
4β-β3β-β5
Additionally, all paths containing only one vertex are palindromic. Listed below are a few paths in the first sample that are not palindromic:
1β-β2β-β3
1β-β2β-β3β-β4
1β-β2β-β3β-β5 | 1,528 |
Title: The Child and Sequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.
Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array *a*[1],<=*a*[2],<=...,<=*a*[*n*]. Then he should perform a sequence of *m* operations. An operation can be one of the following:
1. Print operation *l*,<=*r*. Picks should write down the value of . 1. Modulo operation *l*,<=*r*,<=*x*. Picks should perform assignment *a*[*i*]<==<=*a*[*i*]Β *mod*Β *x* for each *i* (*l*<=β€<=*i*<=β€<=*r*). 1. Set operation *k*,<=*x*. Picks should set the value of *a*[*k*] to *x* (in other words perform an assignment *a*[*k*]<==<=*x*).
Can you help Picks to perform the whole sequence of operations?
Input Specification:
The first line of input contains two integer: *n*,<=*m* (1<=β€<=*n*,<=*m*<=β€<=105). The second line contains *n* integers, separated by space: *a*[1],<=*a*[2],<=...,<=*a*[*n*]Β (1<=β€<=*a*[*i*]<=β€<=109) β initial value of array elements.
Each of the next *m* lines begins with a number *type* .
- If *type*<==<=1, there will be two integers more in the line: *l*,<=*r*Β (1<=β€<=*l*<=β€<=*r*<=β€<=*n*), which correspond the operation 1. - If *type*<==<=2, there will be three integers more in the line: *l*,<=*r*,<=*x*Β (1<=β€<=*l*<=β€<=*r*<=β€<=*n*;Β 1<=β€<=*x*<=β€<=109), which correspond the operation 2. - If *type*<==<=3, there will be two integers more in the line: *k*,<=*x*Β (1<=β€<=*k*<=β€<=*n*;Β 1<=β€<=*x*<=β€<=109), which correspond the operation 3.
Output Specification:
For each operation 1, please print a line containing the answer. Notice that the answer may exceed the 32-bit integer.
Demo Input:
['5 5\n1 2 3 4 5\n2 3 5 4\n3 3 5\n1 2 5\n2 1 3 3\n1 1 3\n', '10 10\n6 9 6 7 6 1 10 10 9 5\n1 3 9\n2 7 10 9\n2 5 10 8\n1 4 7\n3 3 7\n2 7 9 9\n1 2 4\n1 6 6\n1 5 9\n3 1 10\n']
Demo Output:
['8\n5\n', '49\n15\n23\n1\n9\n']
Note:
Consider the first testcase:
- At first, *a*β=β{1,β2,β3,β4,β5}. - After operation 1, *a*β=β{1,β2,β3,β0,β1}. - After operation 2, *a*β=β{1,β2,β5,β0,β1}. - At operation 3, 2β+β5β+β0β+β1β=β8. - After operation 4, *a*β=β{1,β2,β2,β0,β1}. <li> At operation 5, 1β+β2β+β2β=β5. <ul> | 1,529 |
Title: E-reader Display
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers.
The display is represented by *n*<=Γ<=*n* square of pixels, each of which can be either black or white. The display rows are numbered with integers from 1 to *n* upside down, the columns are numbered with integers from 1 to *n* from the left to the right. The display can perform commands like "*x*,<=*y*". When a traditional display fulfills such command, it simply inverts a color of (*x*,<=*y*), where *x* is the row number and *y* is the column number. But in our new display every pixel that belongs to at least one of the segments (*x*,<=*x*)<=-<=(*x*,<=*y*) and (*y*,<=*y*)<=-<=(*x*,<=*y*) (both ends of both segments are included) inverts a color.
For example, if initially a display 5<=Γ<=5 in size is absolutely white, then the sequence of commands (1,<=4), (3,<=5), (5,<=1), (3,<=3) leads to the following changes:
You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.
Input Specification:
The first line contains number *n* (1<=β€<=*n*<=β€<=2000).
Next *n* lines contain *n* characters each: the description of the picture that needs to be shown. "0" represents the white color and "1" represents the black color.
Output Specification:
Print one integer *z* β the least number of commands needed to display the picture.
Demo Input:
['5\n01110\n10010\n10001\n10011\n11110\n']
Demo Output:
['4\n']
Note:
none | 1,530 |
Title: Rusty String
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Grigory loves strings. Recently he found a metal strip on a loft. The strip had length *n* and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written.
Grigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter "V" or "K" on each unreadable position, which values can the period of the resulting string be equal to?
A period of a string is such an integer *d* from 1 to the length of the string that if we put the string shifted by *d* positions to the right on itself, then all overlapping letters coincide. For example, 3 and 5 are periods of "VKKVK".
Input Specification:
There are several (at least one) test cases in the input. The first line contains single integerΒ β the number of test cases.
There is an empty line before each test case. Each test case is described in two lines: the first line contains single integer *n* (1<=β€<=*n*<=β€<=5Β·105)Β β the length of the string, the second line contains the string of length *n*, consisting of letters "V", "K" and characters "?". The latter means the letter on its position is unreadable.
It is guaranteed that the sum of lengths among all test cases doesn't exceed 5Β·105.
For hacks you can only use tests with one test case.
Output Specification:
For each test case print two lines. In the first line print the number of possible periods after we replace each unreadable letter with "V" or "K". In the next line print all these values in increasing order.
Demo Input:
['3\n\xa0\n5\nV??VK\n\xa0\n6\n??????\n\xa0\n4\n?VK?\n']
Demo Output:
['2\n3 5\n6\n1 2 3 4 5 6\n3\n2 3 4\n']
Note:
In the first test case from example we can obtain, for example, "VKKVK", which has periods 3 and 5.
In the second test case we can obtain "VVVVVV" which has all periods from 1 to 6.
In the third test case string "KVKV" has periods 2 and 4, and string "KVKK" has periods 3 and 4. | 1,531 |
Title: Counting Arrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two positive integer numbers *x* and *y*. An array *F* is called an *y*-factorization of *x* iff the following conditions are met:
- There are *y* elements in *F*, and all of them are integer numbers; - .
You have to count the number of pairwise distinct arrays that are *y*-factorizations of *x*. Two arrays *A* and *B* are considered different iff there exists at least one index *i* (1<=β€<=*i*<=β€<=*y*) such that *A**i*<=β <=*B**i*. Since the answer can be very large, print it modulo 109<=+<=7.
Input Specification:
The first line contains one integer *q* (1<=β€<=*q*<=β€<=105) β the number of testcases to solve.
Then *q* lines follow, each containing two integers *x**i* and *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=106). Each of these lines represents a testcase.
Output Specification:
Print *q* integers. *i*-th integer has to be equal to the number of *y**i*-factorizations of *x**i* modulo 109<=+<=7.
Demo Input:
['2\n6 3\n4 2\n']
Demo Output:
['36\n6\n']
Note:
In the second testcase of the example there are six *y*-factorizations:
- {β-β4,ββ-β1}; - {β-β2,ββ-β2}; - {β-β1,ββ-β4}; - {1,β4}; - {2,β2}; - {4,β1}. | 1,532 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
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 Specification:
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 4*n* 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 Specification:
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.
Demo Input:
['1 1\nday\nmay\nsun\nfun\n', '1 1\nday\nmay\ngray\nway\n', '2 1\na\na\na\na\na\na\ne\ne\n', '2 1\nday\nmay\nsun\nfun\ntest\nhill\nfest\nthrill\n']
Demo Output:
['aabb\n', 'aaaa\n', 'aabb\n', 'NO\n']
Note:
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO". | 1,533 |
Title: Tell Your World
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Connect the countless points with lines, till we reach the faraway yonder.
There are *n* points on a coordinate plane, the *i*-th of which being (*i*,<=*y**i*).
Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.
Input Specification:
The first line of input contains a positive integer *n* (3<=β€<=*n*<=β€<=1<=000) β the number of points.
The second line contains *n* space-separated integers *y*1,<=*y*2,<=...,<=*y**n* (<=-<=109<=β€<=*y**i*<=β€<=109) β the vertical coordinates of each point.
Output Specification:
Output "Yes" (without quotes) if it's possible to fulfill the requirements, and "No" otherwise.
You can print each letter in any case (upper or lower).
Demo Input:
['5\n7 5 8 6 9\n', '5\n-1 -2 0 0 -5\n', '5\n5 4 3 2 1\n', '5\n1000000000 0 0 0 0\n']
Demo Output:
['Yes\n', 'No\n', 'No\n', 'Yes\n']
Note:
In the first example, there are five points: (1,β7), (2,β5), (3,β8), (4,β6) and (5,β9). It's possible to draw a line that passes through points 1,β3,β5, and another one that passes through points 2,β4 and is parallel to the first one.
In the second example, while it's possible to draw two lines that cover all points, they cannot be made parallel.
In the third example, it's impossible to satisfy both requirements at the same time. | 1,534 |
Title: Petya and His Friends
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to *n*.
Let us remind you the definition of the greatest common divisor: *GCD*(*a*1,<=...,<=*a**k*)<==<=*d*, where *d* represents such a maximal positive number that each *a**i* (1<=β€<=*i*<=β€<=*k*) is evenly divisible by *d*. At that, we assume that all *a**i*'s are greater than zero.
Knowing that Petya is keen on programming, his friends has agreed beforehand that the 1-st friend gives *a*1 sweets, the 2-nd one gives *a*2 sweets, ..., the *n*-th one gives *a**n* sweets. At the same time, for any *i* and *j* (1<=β€<=*i*,<=*j*<=β€<=*n*) they want the *GCD*(*a**i*,<=*a**j*) not to be equal to 1. However, they also want the following condition to be satisfied: *GCD*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=1. One more: all the *a**i* should be distinct.
Help the friends to choose the suitable numbers *a*1,<=...,<=*a**n*.
Input Specification:
The first line contains an integer *n* (2<=β€<=*n*<=β€<=50).
Output Specification:
If there is no answer, print "-1" without quotes. Otherwise print a set of *n* distinct positive numbers *a*1,<=*a*2,<=...,<=*a**n*. Each line must contain one number. Each number must consist of not more than 100 digits, and must not contain any leading zeros. If there are several solutions to that problem, print any of them.
Do not forget, please, that all of the following conditions must be true:
- For every *i* and *j* (1<=β€<=*i*,<=*j*<=β€<=*n*): *GCD*(*a**i*,<=*a**j*)<=β <=1- *GCD*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=1- For every *i* and *j* (1<=β€<=*i*,<=*j*<=β€<=*n*,<=*i*<=β <=*j*): *a**i*<=β <=*a**j*
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Demo Input:
['3\n', '4\n']
Demo Output:
['99\n55\n11115\n', '385\n360\n792\n8360\n']
Note:
none | 1,535 |
Title: Looking for Owls
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Emperor Palpatine loves owls very much. The emperor has some blueprints with the new Death Star, the blueprints contain *n* distinct segments and *m* distinct circles. We will consider the segments indexed from 1 to *n* in some way and the circles β indexed from 1 to *m* in some way.
Palpatine defines an owl as a set of a pair of distinct circles (*i*,<=*j*) (*i*<=<<=*j*) and one segment *k*, such that:
1. circles *i* and *j* are symmetrical relatively to the straight line containing segment *k*; 1. circles *i* and *j* don't have any common points; 1. circles *i* and *j* have the same radius; 1. segment *k* intersects the segment that connects the centers of circles *i* and *j*.
Help Palpatine, count the number of distinct owls on the picture.
Input Specification:
The first line contains two integers β *n* and *m* (1<=β€<=*n*<=β€<=3Β·105, 2<=β€<=*m*<=β€<=1500).
The next *n* lines contain four integers each, *x*1, *y*1, *x*2, *y*2 β the coordinates of the two endpoints of the segment. It's guaranteed that each segment has positive length.
The next *m* lines contain three integers each, *x**i*, *y**i*, *r**i* β the coordinates of the center and the radius of the *i*-th circle. All coordinates are integers of at most 104 in their absolute value. The radius is a positive integer of at most 104.
It is guaranteed that all segments and all circles are dictinct.
Output Specification:
Print a single number β the answer to the problem.
Please, do not use the %lld specifier to output 64-bit integers is Π‘++. It is preferred to use the cout stream or the %I64d specifier.
Demo Input:
['1 2\n3 2 3 -2\n0 0 2\n6 0 2\n', '3 2\n0 0 0 1\n0 -1 0 1\n0 -1 0 0\n2 0 1\n-2 0 1\n', '1 2\n-1 0 1 0\n-100 0 1\n100 0 1\n']
Demo Output:
['1\n', '3\n', '0\n']
Note:
Here's an owl from the first sample. The owl is sitting and waiting for you to count it. | 1,536 |
Title: Parade
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.
There will be *n* columns participating in the parade, the *i*-th column consists of *l**i* soldiers, who start to march from left leg, and *r**i* soldiers, who start to march from right leg.
The beauty of the parade is calculated by the following formula: if *L* is the total number of soldiers on the parade who start to march from the left leg, and *R* is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |*L*<=-<=*R*|.
No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index *i* and swap values *l**i* and *r**i*.
Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.
Input Specification:
The first line contains single integer *n* (1<=β€<=*n*<=β€<=105)Β β the number of columns.
The next *n* lines contain the pairs of integers *l**i* and *r**i* (1<=β€<=*l**i*,<=*r**i*<=β€<=500)Β β the number of soldiers in the *i*-th column which start to march from the left or the right leg respectively.
Output Specification:
Print single integer *k*Β β the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached.
Consider that columns are numbered from 1 to *n* in the order they are given in the input data.
If there are several answers, print any of them.
Demo Input:
['3\n5 6\n8 9\n10 3\n', '2\n6 5\n5 6\n', '6\n5 9\n1 3\n4 8\n4 5\n23 54\n12 32\n']
Demo Output:
['3\n', '1\n', '0\n']
Note:
In the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5β+β8β+β10β=β23, and from the right legΒ β 6β+β9β+β3β=β18. In this case the beauty of the parade will equal |23β-β18|β=β5.
If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5β+β8β+β3β=β16, and who march from the right legΒ β 6β+β9β+β10β=β25. In this case the beauty equals |16β-β25|β=β9.
It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9. | 1,537 |
Title: Chocolate
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Bob has a rectangular chocolate bar of the size *W*<=Γ<=*H*. He introduced a cartesian coordinate system so that the point (0,<=0) corresponds to the lower-left corner of the bar, and the point (*W*,<=*H*) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line *x*<==<=*x**c* or *y*<==<=*y**c*, where *x**c* and *y**c* are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made *n* breaks and wrote them down in his notebook in arbitrary order. At the end he got *n*<=+<=1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.
Input Specification:
The first line contains 3 integers *W*, *H* and *n* (1<=β€<=*W*,<=*H*,<=*n*<=β€<=100) β width of the bar, height of the bar and amount of breaks. Each of the following *n* lines contains four integers *x**i*,<=1,<=*y**i*,<=1,<=*x**i*,<=2,<=*y**i*,<=2 β coordinates of the endpoints of the *i*-th break (0<=β€<=*x**i*,<=1<=β€<=*x**i*,<=2<=β€<=*W*,<=0<=β€<=*y**i*,<=1<=β€<=*y**i*,<=2<=β€<=*H*, or *x**i*,<=1<==<=*x**i*,<=2, or *y**i*,<=1<==<=*y**i*,<=2). Breaks are given in arbitrary order.
It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.
Output Specification:
Output *n*<=+<=1 numbers β areas of the resulting parts in the increasing order.
Demo Input:
['2 2 2\n1 0 1 2\n0 1 1 1\n', '2 2 3\n1 0 1 2\n0 1 1 1\n1 1 2 1\n', '2 4 2\n0 1 2 1\n0 3 2 3\n']
Demo Output:
['1 1 2 ', '1 1 1 1 ', '2 2 4 ']
Note:
none | 1,538 |
Title: Shark
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.
Max is a young biologist. For $n$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $k$ that if the shark in some day traveled the distance strictly less than $k$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $k$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $k$.
The shark never returned to the same location after it has moved from it. Thus, in the sequence of $n$ days we can find consecutive nonempty segments when the shark traveled the distance less than $k$ in each of the days: each such segment corresponds to one location. Max wants to choose such $k$ that the lengths of all such segments are equal.
Find such integer $k$, that the number of locations is as large as possible. If there are several such $k$, print the smallest one.
Input Specification:
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) β the number of days.
The second line contains $n$ distinct positive integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) β the distance traveled in each of the day.
Output Specification:
Print a single integer $k$, such that
1. the shark was in each location the same number of days, 1. the number of locations is maximum possible satisfying the first condition, 1. $k$ is smallest possible satisfying the first and second conditions.
Demo Input:
['8\n1 2 7 3 4 8 5 6\n', '6\n25 1 2 3 14 36\n']
Demo Output:
['7', '2']
Note:
In the first example the shark travels inside a location on days $1$ and $2$ (first location), then on $4$-th and $5$-th days (second location), then on $7$-th and $8$-th days (third location). There are three locations in total.
In the second example the shark only moves inside a location on the $2$-nd day, so there is only one location. | 1,539 |
Title: Empire Strikes Back
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In a far away galaxy there is war again. The treacherous Republic made *k* precision strikes of power *a**i* on the Empire possessions. To cope with the republican threat, the Supreme Council decided to deal a decisive blow to the enemy forces.
To successfully complete the conflict, the confrontation balance after the blow should be a positive integer. The balance of confrontation is a number that looks like , where *p*<==<=*n*! (*n* is the power of the Imperial strike), . After many years of war the Empire's resources are low. So to reduce the costs, *n* should be a minimum positive integer that is approved by the commanders.
Help the Empire, find the minimum positive integer *n*, where the described fraction is a positive integer.
Input Specification:
The first line contains integer *k* (1<=β€<=*k*<=β€<=106). The second line contains *k* integers *a*1,<=*a*2,<=...,<=*a**k* (1<=β€<=*a**i*<=β€<=107).
Output Specification:
Print the minimum positive integer *n*, needed for the Empire to win.
Please, do not use the %lld to read or write 64-but integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Demo Input:
['2\n1000 1000\n', '1\n2\n']
Demo Output:
['2000', '2']
Note:
none | 1,540 |
Title: Little Elephant and Cards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Little Elephant loves to play with color cards.
He has *n* cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).
Help the Little Elephant to find the minimum number of moves needed to make the set of *n* cards funny.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=105) β the number of the cards. The following *n* lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β colors of both sides. The first number in a line is the color of the front of the card, the second one β of the back. The color of the front of the card may coincide with the color of the back of the card.
The numbers in the lines are separated by single spaces.
Output Specification:
On a single line print a single integer β the sought minimum number of moves. If it is impossible to make the set funny, print -1.
Demo Input:
['3\n4 7\n4 7\n7 4\n', '5\n4 7\n7 4\n2 11\n9 7\n1 1\n']
Demo Output:
['0\n', '2\n']
Note:
In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.
In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. | 1,541 |
Title: Flea
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
It is known that fleas in Berland can jump only vertically and horizontally, and the length of the jump is always equal to *s* centimeters. A flea has found herself at the center of some cell of the checked board of the size *n*<=Γ<=*m* centimeters (each cell is 1<=Γ<=1 centimeters). She can jump as she wishes for an arbitrary number of times, she can even visit a cell more than once. The only restriction is that she cannot jump out of the board.
The flea can count the amount of cells that she can reach from the starting position (*x*,<=*y*). Let's denote this amount by *d**x*,<=*y*. Your task is to find the number of such starting positions (*x*,<=*y*), which have the maximum possible value of *d**x*,<=*y*.
Input Specification:
The first line contains three integers *n*, *m*, *s* (1<=β€<=*n*,<=*m*,<=*s*<=β€<=106) β length of the board, width of the board and length of the flea's jump.
Output Specification:
Output the only integer β the number of the required starting positions of the flea.
Demo Input:
['2 3 1000000\n', '3 3 2\n']
Demo Output:
['6\n', '4\n']
Note:
none | 1,542 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Yasin has an array *a* containing *n* integers. Yasin is a 5 year old, so he loves ultimate weird things.
Yasin denotes weirdness of an array as maximum *gcd*(*a**i*,<=<=*a**j*) value among all 1<=β€<=*i*<=<<=*j*<=β€<=*n*. For *n*<=β€<=1 weirdness is equal to 0, *gcd*(*x*,<=<=*y*) is the greatest common divisor of integers *x* and *y*.
He also defines the ultimate weirdness of an array. Ultimate weirdness is where *f*(*i*,<=<=*j*) is weirdness of the new array *a* obtained by removing all elements between *i* and *j* inclusive, so new array is [*a*1... *a**i*<=-<=1,<=*a**j*<=+<=1... *a**n*].
Since 5 year old boys can't code, Yasin asks for your help to find the value of ultimate weirdness of the given array *a*!
Input Specification:
The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=200<=000)Β β the number of elements in *a*.
The next line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=200<=000), where the *i*-th number is equal to the *i*-th element of the array *a*. It is guaranteed that all *a**i* are distinct.
Output Specification:
Print a single line containing the value of ultimate weirdness of the array *a*.
Demo Input:
['3\n2 6 3\n']
Demo Output:
['6\n']
Note:
Consider the first sample.
- *f*(1,ββ1) is equal to 3. - *f*(2,ββ2) is equal to 1. - *f*(3,ββ3) is equal to 2. - *f*(1,ββ2), *f*(1,ββ3) and *f*(2,ββ3) are equal to 0. | 1,543 |
Title: DZY Loves Physics
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
Once DZY got a graph *G*, now he wants to find a connected induced subgraph *G*' of the graph, such that the density of *G*' is as large as possible.
An induced subgraph *G*'(*V*',<=*E*') of a graph *G*(*V*,<=*E*) is a graph that satisfies:
- ; - edge if and only if , and edge ; - the value of an edge in *G*' is the same as the value of the corresponding edge in *G*, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
Input Specification:
The first line contains two space-separated integers *n*Β (1<=β€<=*n*<=β€<=500), . Integer *n* represents the number of nodes of the graph *G*, *m* represents the number of edges.
The second line contains *n* space-separated integers *x**i*Β (1<=β€<=*x**i*<=β€<=106), where *x**i* represents the value of the *i*-th node. Consider the graph nodes are numbered from 1 to *n*.
Each of the next *m* lines contains three space-separated integers *a**i*,<=*b**i*,<=*c**i*Β (1<=β€<=*a**i*<=<<=*b**i*<=β€<=*n*;Β 1<=β€<=*c**i*<=β€<=103), denoting an edge between node *a**i* and *b**i* with value *c**i*. The graph won't contain multiple edges.
Output Specification:
Output a real number denoting the answer, with an absolute or relative error of at most 10<=-<=9.
Demo Input:
['1 0\n1\n', '2 1\n1 2\n1 2 1\n', '5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63\n']
Demo Output:
['0.000000000000000\n', '3.000000000000000\n', '2.965517241379311\n']
Note:
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | 1,544 |
Title: Sagheer and Apple Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sagheer is playing a game with his best friend Soliman. He brought a tree with *n* nodes numbered from 1 to *n* and rooted at node 1. The *i*-th node has *a**i* apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).
Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.
In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things:
1. eat the apples, if the node is a leaf. 1. move the apples to one of the children, if the node is non-leaf.
Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes *u* and *v* and swap the apples of *u* with the apples of *v*.
Can you help Sagheer count the number of ways to make the swap (i.e. to choose *u* and *v*) after which he will win the game if both players play optimally? (*u*,<=*v*) and (*v*,<=*u*) are considered to be the same pair.
Input Specification:
The first line will contain one integer *n* (2<=β€<=*n*<=β€<=105) β the number of nodes in the apple tree.
The second line will contain *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=107) β the number of apples on each node of the tree.
The third line will contain *n*<=-<=1 integers *p*2,<=*p*3,<=...,<=*p**n* (1<=β€<=*p**i*<=β€<=*n*) β the parent of each node of the tree. Node *i* has parent *p**i* (for 2<=β€<=*i*<=β€<=*n*). Node 1 is the root of the tree.
It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.
Output Specification:
On a single line, print the number of different pairs of nodes (*u*,<=*v*), *u*<=β <=*v* such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (*u*,<=*v*) and (*v*,<=*u*) are considered to be the same pair.
Demo Input:
['3\n2 2 3\n1 1\n', '3\n1 2 3\n1 1\n', '8\n7 2 2 5 4 3 1 1\n1 1 1 4 4 5 6\n']
Demo Output:
['1\n', '0\n', '4\n']
Note:
In the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.
In the second sample, There is no swap that will make Sagheer win the game.
Note that Sagheer must make the swap even if he can win with the initial tree. | 1,545 |
Title: Turn the Rectangles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are $n$ rectangles in a row. You can either turn each rectangle by $90$ degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input Specification:
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$)Β β the number of rectangles.
Each of the next $n$ lines contains two integers $w_i$ and $h_i$ ($1 \leq w_i, h_i \leq 10^9$)Β β the width and the height of the $i$-th rectangle.
Output Specification:
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Demo Input:
['3\n3 4\n4 6\n3 5\n', '2\n3 4\n5 5\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one. | 1,546 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Everyone knows that DNA strands consist of nucleotides. There are four types of nucleotides: "A", "T", "G", "C". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string *s* initially.
Evolution of the species is described as a sequence of changes in the DNA. Every change is a change of some nucleotide, for example, the following change can happen in DNA strand "AAGC": the second nucleotide can change to "T" so that the resulting DNA strand is "ATGC".
Scientists know that some segments of the DNA strand can be affected by some unknown infections. They can represent an infection as a sequence of nucleotides. Scientists are interested if there are any changes caused by some infections. Thus they sometimes want to know the value of impact of some infection to some segment of the DNA. This value is computed as follows:
- Let the infection be represented as a string *e*, and let scientists be interested in DNA strand segment starting from position *l* to position *r*, inclusive. - Prefix of the string *eee*... (i.e. the string that consists of infinitely many repeats of string *e*) is written under the string *s* from position *l* to position *r*, inclusive. - The value of impact is the number of positions where letter of string *s* coincided with the letter written under it.
Being a developer, Innokenty is interested in bioinformatics also, so the scientists asked him for help. Innokenty is busy preparing VK Cup, so he decided to delegate the problem to the competitors. Help the scientists!
Input Specification:
The first line contains the string *s* (1<=β€<=|*s*|<=β€<=105) that describes the initial DNA strand. It consists only of capital English letters "A", "T", "G" and "C".
The next line contains single integer *q* (1<=β€<=*q*<=β€<=105)Β β the number of events.
After that, *q* lines follow, each describes one event. Each of the lines has one of two formats:
- 1Β xΒ c, where *x* is an integer (1<=β€<=*x*<=β€<=|*s*|), and *c* is a letter "A", "T", "G" or "C", which means that there is a change in the DNA: the nucleotide at position *x* is now *c*. - 2Β lΒ rΒ e, where *l*, *r* are integers (1<=β€<=*l*<=β€<=*r*<=β€<=|*s*|), and *e* is a string of letters "A", "T", "G" and "C" (1<=β€<=|*e*|<=β€<=10), which means that scientists are interested in the value of impact of infection *e* to the segment of DNA strand from position *l* to position *r*, inclusive.
Output Specification:
For each scientists' query (second type query) print a single integer in a new lineΒ β the value of impact of the infection on the DNA.
Demo Input:
['ATGCATGC\n4\n2 1 8 ATGC\n2 2 6 TTT\n1 4 T\n2 2 6 TA\n', 'GAGTTGTTAA\n6\n2 3 4 TATGGTG\n1 1 T\n1 6 G\n2 5 9 AGTAATA\n1 10 G\n2 2 6 TTGT\n']
Demo Output:
['8\n2\n4\n', '0\n3\n1\n']
Note:
Consider the first example. In the first query of second type all characters coincide, so the answer is 8. In the second query we compare string "TTTTT..." and the substring "TGCAT". There are two matches. In the third query, after the DNA change, we compare string "TATAT..."' with substring "TGTAT". There are 4 matches. | 1,547 |
Title: Gleb And Pizza
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.
The pizza is a circle of radius *r* and center at the origin. Pizza consists of the main part β circle of radius *r*<=-<=*d* with center at the origin, and crust around the main part of the width *d*. Pieces of sausage are also circles. The radius of the *i*Β -th piece of the sausage is *r**i*, and the center is given as a pair (*x**i*, *y**i*).
Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.
Input Specification:
First string contains two integer numbers *r* and *d* (0<=β€<=*d*<=<<=*r*<=β€<=500)Β β the radius of pizza and the width of crust.
Next line contains one integer number *n*Β β the number of pieces of sausage (1<=β€<=*n*<=β€<=105).
Each of next *n* lines contains three integer numbers *x**i*, *y**i* and *r**i* (<=-<=500<=β€<=*x**i*,<=*y**i*<=β€<=500, 0<=β€<=*r**i*<=β€<=500), where *x**i* and *y**i* are coordinates of the center of *i*-th peace of sausage, *r**i*Β β radius of *i*-th peace of sausage.
Output Specification:
Output the number of pieces of sausage that lay on the crust.
Demo Input:
['8 4\n7\n7 8 1\n-7 3 2\n0 2 1\n0 -2 2\n-3 -3 1\n0 6 2\n5 3 1\n', '10 8\n4\n0 0 9\n0 0 10\n1 0 1\n1 0 2\n']
Demo Output:
['2\n', '0\n']
Note:
Below is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust. | 1,548 |
Title: MUH and Lots and Lots of Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to do some painting. As they were trying to create their first masterpiece, they made a draft on a piece of paper. The draft consists of *n* segments. Each segment was either horizontal or vertical. Now the friends want to simplify the draft by deleting some segments or parts of segments so that the final masterpiece meets three conditions:
1. Horace wants to be able to paint the whole picture in one stroke: by putting the brush on the paper and never taking it off until the picture is ready. The brush can paint the same place multiple times. That's why all the remaining segments must form a single connected shape. 1. Menshykov wants the resulting shape to be simple. He defines a simple shape as a shape that doesn't contain any cycles. 1. Initially all the segment on the draft have integer startpoint and endpoint coordinates. Uslada doesn't like real coordinates and she wants this condition to be fulfilled after all the changes.
As in other parts the draft is already beautiful, the friends decided to delete such parts of the draft that the sum of lengths of the remaining segments is as large as possible. Your task is to count this maximum sum of the lengths that remain after all the extra segments are removed.
Input Specification:
The first line of the input contains integer *n* (1<=β€<=*n*<=β€<=2Β·105) β the number of segments on the draft. The next *n* lines contain four integers each: *x*1, *y*1, *x*2, *y*2 (<=-<=109<=β€<=*x*1<=β€<=*x*2<=β€<=109;Β <=-<=109<=β€<=*y*1<=β€<=*y*2<=β€<=109) β the two startpoint and the two endpoint coordinates of a segment. All segments are non-degenerative and either are strictly horizontal or strictly vertical.
No two horizontal segments share common points. No two vertical segments share common points.
Output Specification:
Print a single integer β the maximum sum of lengths for the remaining segments.
Demo Input:
['2\n0 0 0 1\n1 0 1 1\n', '4\n0 0 1 0\n0 0 0 1\n1 -1 1 2\n0 1 1 1\n']
Demo Output:
['1', '5']
Note:
The shapes that you can get in the two given samples are:
In the first sample you need to delete any segment as the two segments together do not form a single connected shape.
In the second sample the initial segments form a cycle, there are four ways to break the cycle: delete the first, second or fourth segment altogether or delete the middle of the third segment. The last way is shown on the picture. | 1,549 |
Title: Vacations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has *n* days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this *n* days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the *i*-th day there are four options:
1. on this day the gym is closed and the contest is not carried out; 1. on this day the gym is closed and the contest is carried out; 1. on this day the gym is open and the contest is not carried out; 1. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input Specification:
The first line contains a positive integer *n* (1<=β€<=*n*<=β€<=100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=3) separated by space, where:
- *a**i* equals 0, if on the *i*-th day of vacations the gym is closed and the contest is not carried out; - *a**i* equals 1, if on the *i*-th day of vacations the gym is closed, but the contest is carried out; - *a**i* equals 2, if on the *i*-th day of vacations the gym is open and the contest is not carried out; - *a**i* equals 3, if on the *i*-th day of vacations the gym is open and the contest is carried out.
Output Specification:
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
- to do sport on any two consecutive days, - to write the contest on any two consecutive days.
Demo Input:
['4\n1 3 2 0\n', '7\n1 3 3 2 1 2 3\n', '2\n2 2\n']
Demo Output:
['2\n', '0\n', '1\n']
Note:
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. | 1,550 |
Title: Devu, the Dumb Guy
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him *n* subjects, the *i**th* subject has *c**i* chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is *x* hours. In other words he can learn a chapter of a particular subject in *x* hours.
Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.
You can teach him the *n* subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.
Please be careful that answer might not fit in 32 bit data type.
Input Specification:
The first line will contain two space separated integers *n*, *x* (1<=β€<=*n*,<=*x*<=β€<=105). The next line will contain *n* space separated integers: *c*1,<=*c*2,<=...,<=*c**n* (1<=β€<=*c**i*<=β€<=105).
Output Specification:
Output a single integer representing the answer to the problem.
Demo Input:
['2 3\n4 1\n', '4 2\n5 1 2 1\n', '3 3\n1 1 1\n']
Demo Output:
['11\n', '10\n', '6\n']
Note:
Look at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2βΓβ1β=β2 hours. Hence you will need to spend 12β+β2β=β14 hours.
Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3βΓβ1β=β3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2βΓβ4β=β8 hours. Hence you will need to spend 11 hours.
So overall, minimum of both the cases is 11 hours.
Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours. | 1,551 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the year of $30XX$ participants of some world programming championship live in a single large hotel. The hotel has $n$ floors. Each floor has $m$ sections with a single corridor connecting all of them. The sections are enumerated from $1$ to $m$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $n$ and width $m$. We can denote sections with pairs of integers $(i, j)$, where $i$ is the floor, and $j$ is the section number on the floor.
The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $(1, x)$, $(2, x)$, $\ldots$, $(n, x)$ for some $x$ between $1$ and $m$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $v$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.
You are to process $q$ queries. Each query is a question "what is the minimum time needed to go from a room in section $(x_1, y_1)$ to a room in section $(x_2, y_2)$?"
Input Specification:
The first line contains five integers $n, m, c_l, c_e, v$ ($2 \leq n, m \leq 10^8$, $0 \leq c_l, c_e \leq 10^5$, $1 \leq c_l + c_e \leq m - 1$, $1 \leq v \leq n - 1$)Β β the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.
The second line contains $c_l$ integers $l_1, \ldots, l_{c_l}$ in increasing order ($1 \leq l_i \leq m$), denoting the positions of the stairs. If $c_l = 0$, the second line is empty.
The third line contains $c_e$ integers $e_1, \ldots, e_{c_e}$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $l_i$ and $e_i$ are distinct.
The fourth line contains a single integer $q$ ($1 \leq q \leq 10^5$)Β β the number of queries.
The next $q$ lines describe queries. Each of these lines contains four integers $x_1, y_1, x_2, y_2$ ($1 \leq x_1, x_2 \leq n$, $1 \leq y_1, y_2 \leq m$)Β β the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i.Β e. $y_1$ and $y_2$ are not among $l_i$ and $e_i$.
Output Specification:
Print $q$ integers, one per lineΒ β the answers for the queries.
Demo Input:
['5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3\n']
Demo Output:
['7\n5\n4\n']
Note:
In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.
In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. | 1,552 |
Title: Restructuring Company
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Even the most successful company can go through a crisis period when you have to make a hard decision β to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.
There are *n* people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of *n* departments, one person in each).
However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use *team*(*person*) to represent a team where person *person* works. A crisis manager can make decisions of two types:
1. Merge departments *team*(*x*) and *team*(*y*) into one large department containing all the employees of *team*(*x*) and *team*(*y*), where *x* and *y* (1<=β€<=*x*,<=*y*<=β€<=*n*) β are numbers of two of some company employees. If *team*(*x*) matches *team*(*y*), then nothing happens. 1. Merge departments *team*(*x*),<=*team*(*x*<=+<=1),<=...,<=*team*(*y*), where *x* and *y* (1<=β€<=*x*<=β€<=*y*<=β€<=*n*) β the numbers of some two employees of the company.
At that the crisis manager can sometimes wonder whether employees *x* and *y* (1<=β€<=*x*,<=*y*<=β€<=*n*) work at the same department.
Help the crisis manager and answer all of his queries.
Input Specification:
The first line of the input contains two integers *n* and *q* (1<=β€<=*n*<=β€<=200<=000, 1<=β€<=*q*<=β€<=500<=000) β the number of the employees of the company and the number of queries the crisis manager has.
Next *q* lines contain the queries of the crisis manager. Each query looks like *type*Β *x*Β *y*, where . If *type*<==<=1 or *type*<==<=2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If *type*<==<=3, then your task is to determine whether employees *x* and *y* work at the same department. Note that *x* can be equal to *y* in the query of any type.
Output Specification:
For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.
Demo Input:
['8 6\n3 2 5\n1 2 5\n3 2 5\n2 4 7\n2 1 2\n3 1 7\n']
Demo Output:
['NO\nYES\nYES\n']
Note:
none | 1,553 |
Title: Arpaβs abnormal DNA and Mehrdadβs deep interest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
All of us know that girls in Arpaβs land are... ok, youβve got the idea :D
Anyone knows that Arpa isn't a normal man, he is ... well, sorry, I can't explain it more. Mehrdad is interested about the reason, so he asked Sipa, one of the best biology scientists in Arpa's land, for help. Sipa has a DNA editor.
Sipa put Arpa under the DNA editor. DNA editor showed Arpa's DNA as a string *S* consisting of *n* lowercase English letters. Also Sipa has another DNA *T* consisting of lowercase English letters that belongs to a normal man.
Now there are (*n*<=+<=1) options to change Arpa's DNA, numbered from 0 to *n*. *i*-th of them is to put *T* between *i*-th and (*i*<=+<=1)-th characters of *S* (0<=β€<=*i*<=β€<=*n*). If *i*<==<=0, *T* will be put before *S*, and if *i*<==<=*n*, it will be put after *S*.
Mehrdad wants to choose the most interesting option for Arpa's DNA among these *n*<=+<=1 options. DNA *A* is more interesting than *B* if *A* is lexicographically smaller than *B*. Mehrdad asked Sipa *q* questions:
Given integers *l*,<=*r*,<=*k*,<=*x*,<=*y*, what is the most interesting option if we only consider such options *i* that *l*<=β€<=*i*<=β€<=*r* and ? If there are several most interesting options, Mehrdad wants to know one with the smallest number *i*.
Since Sipa is a biology scientist but not a programmer, you should help him.
Input Specification:
The first line contains strings *S*, *T* and integer *q* (1<=β€<=|*S*|,<=|*T*|,<=*q*<=β€<=105)Β β Arpa's DNA, the DNA of a normal man, and the number of Mehrdad's questions. The strings *S* and *T* consist only of small English letters.
Next *q* lines describe the Mehrdad's questions. Each of these lines contain five integers *l*,<=*r*,<=*k*,<=*x*,<=*y* (0<=β€<=*l*<=β€<=*r*<=β€<=*n*, 1<=β€<=*k*<=β€<=*n*, 0<=β€<=*x*<=β€<=*y*<=<<=*k*).
Output Specification:
Print *q* integers. The *j*-th of them should be the number *i* of the most interesting option among those that satisfy the conditions of the *j*-th question. If there is no option *i* satisfying the conditions in some question, print -1.
Demo Input:
['abc d 4\n0 3 2 0 0\n0 3 1 0 0\n1 2 1 0 0\n0 1 3 2 2\n', 'abbbbbbaaa baababaaab 10\n1 2 1 0 0\n2 7 8 4 7\n2 3 9 2 8\n3 4 6 1 1\n0 8 5 2 4\n2 8 10 4 7\n7 10 1 0 0\n1 4 6 0 2\n0 9 8 0 6\n4 8 5 0 1\n']
Demo Output:
['2 3 2 -1 \n', '1 4 2 -1 2 4 10 1 1 5 \n']
Note:
Explanation of first sample case:
In the first question Sipa has two options: dabc (*i*β=β0) and abdc (*i*β=β2). The latter (abcd) is better than abdc, so answer is 2.
In the last question there is no *i* such that 0ββ€β*i*ββ€β1 and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7cc85c61d920b3b180f2ce094f0077871cd4c4d7.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | 1,554 |
Title: Willem, Chtholly and Seniorious
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
β Willem...
β What's the matter?
β It seems that there's something wrong with Seniorious...
β I'll have a look...
Seniorious is made by linking special talismans in particular order.
After over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly.
Seniorious has *n* pieces of talisman. Willem puts them in a line, the *i*-th of which is an integer *a**i*.
In order to maintain it, Willem needs to perform *m* operations.
There are four types of operations:
- 1 *l* *r* *x*: For each *i* such that *l*<=β€<=*i*<=β€<=*r*, assign *a**i*<=+<=*x* to *a**i*.- 2 *l* *r* *x*: For each *i* such that *l*<=β€<=*i*<=β€<=*r*, assign *x* to *a**i*.- 3 *l* *r* *x*: Print the *x*-th smallest number in the index range [*l*,<=*r*], i.e. the element at the *x*-th position if all the elements *a**i* such that *l*<=β€<=*i*<=β€<=*r* are taken and sorted into an array of non-decreasing integers. It's guaranteed that 1<=β€<=*x*<=β€<=*r*<=-<=*l*<=+<=1.- 4 *l* *r* *x* *y*: Print the sum of the *x*-th power of *a**i* such that *l*<=β€<=*i*<=β€<=*r*, modulo *y*, i.e. .
Input Specification:
The only line contains four integers *n*,<=*m*,<=*seed*,<=*v**max* (1<=β€<=*n*,<=*m*<=β€<=105,<=0<=β€<=*seed*<=<<=109<=+<=7,<=1<=β€<=*vmax*<=β€<=109).
The initial values and operations are generated using following pseudo code:
Here *op* is the type of the operation mentioned in the legend.
Output Specification:
For each operation of types 3 or 4, output a line containing the answer.
Demo Input:
['10 10 7 9\n', '10 10 9 9\n']
Demo Output:
['2\n1\n0\n3\n', '1\n1\n3\n3\n']
Note:
In the first example, the initial array is {8,β9,β7,β2,β3,β1,β5,β6,β4,β8}.
The operations are:
- 2 6 7 9 - 1 3 10 8 - 4 4 6 2 4 - 1 4 5 8 - 2 1 7 1 - 4 7 9 4 4 - 1 2 7 9 - 4 5 8 1 1 - 2 5 7 5 - 4 3 10 8 5 | 1,555 |
Title: Beautiful numbers
Time Limit: 4 seconds
Memory Limit: 256 megabytes
Problem Description:
Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.
Input Specification:
The first line of the input contains the number of cases *t* (1<=β€<=*t*<=β€<=10). Each of the next *t* lines contains two natural numbers *l**i* and *r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=9<=Β·1018).
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Output Specification:
Output should contain *t* numbers β answers to the queries, one number per line β quantities of beautiful numbers in given intervals (from *l**i* to *r**i*, inclusively).
Demo Input:
['1\n1 9\n', '1\n12 15\n']
Demo Output:
['9\n', '2\n']
Note:
none | 1,556 |
Title: Game on Paper
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.
He took a checkered white square piece of paper, consisting of *n*<=Γ<=*n* cells. After that, he started to paint the white cells black one after the other. In total he painted *m* different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him.
Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*<=β€<=1000, 1<=β€<=*m*<=β€<=*min*(*n*Β·*n*,<=105)) β the size of the squared piece of paper and the number of moves, correspondingly.
Then, *m* lines contain the description of the moves. The *i*-th line contains two integers *x**i*, *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=*n*) β the number of row and column of the square that gets painted on the *i*-th move.
All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom.
Output Specification:
On a single line print the answer to the problem β the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1.
Demo Input:
['4 11\n1 1\n1 2\n1 3\n2 2\n2 3\n1 4\n2 4\n3 4\n3 2\n3 3\n4 1\n', '4 12\n1 1\n1 2\n1 3\n2 2\n2 3\n1 4\n2 4\n3 4\n3 2\n4 2\n4 1\n3 1\n']
Demo Output:
['10\n', '-1\n']
Note:
none | 1,557 |
Title: World Tour
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A famous sculptor Cicasso goes to a world tour!
Well, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country β Berland.
Cicasso is very devoted to his work and he wants to be distracted as little as possible. Therefore he will visit only four cities. These cities will be different, so no one could think that he has "favourites". Of course, to save money, he will chose the shortest paths between these cities. But as you have probably guessed, Cicasso is a weird person. Although he doesn't like to organize exhibitions, he likes to travel around the country and enjoy its scenery. So he wants the total distance which he will travel to be as large as possible. However, the sculptor is bad in planning, so he asks you for help.
There are *n* cities and *m* one-way roads in Berland. You have to choose four different cities, which Cicasso will visit and also determine the order in which he will visit them. So that the total distance he will travel, if he visits cities in your order, starting from the first city in your list, and ending in the last, choosing each time the shortest route between a pair of cities β will be the largest.
Note that intermediate routes may pass through the cities, which are assigned to the tour, as well as pass twice through the same city. For example, the tour can look like that: . Four cities in the order of visiting marked as overlines: [1,<=5,<=2,<=4].
Note that Berland is a high-tech country. So using nanotechnologies all roads were altered so that they have the same length. For the same reason moving using regular cars is not very popular in the country, and it can happen that there are such pairs of cities, one of which generally can not be reached by car from the other one. However, Cicasso is very conservative and cannot travel without the car. Choose cities so that the sculptor can make the tour using only the automobile. It is guaranteed that it is always possible to do.
Input Specification:
In the first line there is a pair of integers *n* and *m* (4<=β€<=*n*<=β€<=3000,<=3<=β€<=*m*<=β€<=5000) β a number of cities and one-way roads in Berland.
Each of the next *m* lines contains a pair of integers *u**i*,<=*v**i* (1<=β€<=*u**i*,<=*v**i*<=β€<=*n*) β a one-way road from the city *u**i* to the city *v**i*. Note that *u**i* and *v**i* are not required to be distinct. Moreover, it can be several one-way roads between the same pair of cities.
Output Specification:
Print four integers β numbers of cities which Cicasso will visit according to optimal choice of the route. Numbers of cities should be printed in the order that Cicasso will visit them. If there are multiple solutions, print any of them.
Demo Input:
['8 9\n1 2\n2 3\n3 4\n4 1\n4 5\n5 6\n6 7\n7 8\n8 5\n']
Demo Output:
['2 1 8 7\n']
Note:
Let *d*(*x*,β*y*) be the shortest distance between cities *x* and *y*. Then in the example *d*(2,β1)β=β3,β*d*(1,β8)β=β7,β*d*(8,β7)β=β3. The total distance equals 13. | 1,558 |
Title: Parcels
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Jaroslav owns a small courier service. He has recently got and introduced a new system of processing parcels. Each parcel is a box, the box has its weight and strength. The system works as follows. It originally has an empty platform where you can put boxes by the following rules:
- If the platform is empty, then the box is put directly on the platform, otherwise it is put on the topmost box on the platform. - The total weight of all boxes on the platform cannot exceed the strength of platform *S* at any time. - The strength of any box of the platform at any time must be no less than the total weight of the boxes that stand above.
You can take only the topmost box from the platform.
The system receives *n* parcels, the *i*-th parcel arrives exactly at time *in**i*, its weight and strength are equal to *w**i* and *s**i*, respectively. Each parcel has a value of *v**i* bourles. However, to obtain this value, the system needs to give the parcel exactly at time *out**i*, otherwise Jaroslav will get 0 bourles for it. Thus, Jaroslav can skip any parcel and not put on the platform, formally deliver it at time *in**i* and not get anything for it.
Any operation in the problem is performed instantly. This means that it is possible to make several operations of receiving and delivering parcels at the same time and in any order.
Please note that the parcel that is delivered at time *out**i*, immediately gets outside of the system, and the following activities taking place at the same time are made ββwithout taking it into consideration.
Since the system is very complex, and there are a lot of received parcels, Jaroslav asks you to say what maximum amount of money he can get using his system.
Input Specification:
The first line of the input contains two space-separated integers *n* and *S* (1<=β€<=*n*<=β€<=500, 0<=β€<=*S*<=β€<=1000). Then *n* lines follow, the *i*-th line contains five space-separated integers: *in**i*, *out**i*, *w**i*, *s**i* and *v**i* (0<=β€<=*in**i*<=<<=*out**i*<=<<=2*n*, 0<=β€<=*w**i*,<=*s**i*<=β€<=1000, 1<=β€<=*v**i*<=β€<=106). It is guaranteed that for any *i* and *j* (*i*<=β <=*j*) either *in**i*<=β <=*in**j*, or *out**i*<=β <=*out**j*.
Output Specification:
Print a single number β the maximum sum in bourles that Jaroslav can get.
Demo Input:
['3 2\n0 1 1 1 1\n1 2 1 1 1\n0 2 1 1 1\n', '5 5\n0 6 1 2 1\n1 2 1 1 1\n1 3 1 1 1\n3 6 2 1 2\n4 5 1 1 1\n']
Demo Output:
['3\n', '5\n']
Note:
Note to the second sample (*T* is the moment in time):
- *T*β=β0: The first parcel arrives, we put in on the first platform. - *T*β=β1: The second and third parcels arrive, we put the third one on the current top (i.e. first) parcel on the platform, then we put the secod one on the third one. Now the first parcel holds weight *w*<sub class="lower-index">2</sub>β+β*w*<sub class="lower-index">3</sub>β=β2 and the third parcel holds *w*<sub class="lower-index">2</sub>β=β1. - *T*β=β2: We deliver the second parcel and get *v*<sub class="lower-index">2</sub>β=β1 bourle. Now the first parcel holds weight *w*<sub class="lower-index">3</sub>β=β1, the third one holds 0. - *T*β=β3: The fourth parcel comes. First we give the third parcel and get *v*<sub class="lower-index">3</sub>β=β1 bourle. Now the first parcel holds weight 0. We put the fourth parcel on it β the first one holds *w*<sub class="lower-index">4</sub>β=β2. - *T*β=β4: The fifth parcel comes. We cannot put it on the top parcel of the platform as in that case the first parcel will carry weight *w*<sub class="lower-index">4</sub>β+β*w*<sub class="lower-index">5</sub>β=β3, that exceed its strength *s*<sub class="lower-index">1</sub>β=β2, that's unacceptable. We skip the fifth parcel and get nothing for it. - *T*β=β5: Nothing happens. - *T*β=β6: We deliver the fourth, then the first parcel and get *v*<sub class="lower-index">1</sub>β+β*v*<sub class="lower-index">4</sub>β=β3 bourles for them.
Note that you could have skipped the fourth parcel and got the fifth one instead, but in this case the final sum would be 4 bourles. | 1,559 |
Title: Yet Another Array Queries Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* of size *n*, and *q* queries to it. There are queries of two types:
- 1 *l**i* *r**i* β perform a cyclic shift of the segment [*l**i*,<=*r**i*] to the right. That is, for every *x* such that *l**i*<=β€<=*x*<=<<=*r**i* new value of *a**x*<=+<=1 becomes equal to old value of *a**x*, and new value of *a**l**i* becomes equal to old value of *a**r**i*; - 2 *l**i* *r**i* β reverse the segment [*l**i*,<=*r**i*].
There are *m* important indices in the array *b*1, *b*2, ..., *b**m*. For each *i* such that 1<=β€<=*i*<=β€<=*m* you have to output the number that will have index *b**i* in the array after all queries are performed.
Input Specification:
The first line contains three integer numbers *n*, *q* and *m* (1<=β€<=*n*,<=*q*<=β€<=2Β·105, 1<=β€<=*m*<=β€<=100).
The second line contains *n* integer numbers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=109).
Then *q* lines follow. *i*-th of them contains three integer numbers *t**i*, *l**i*, *r**i*, where *t**i* is the type of *i*-th query, and [*l**i*,<=*r**i*] is the segment where this query is performed (1<=β€<=*t**i*<=β€<=2, 1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*).
The last line contains *m* integer numbers *b*1, *b*2, ..., *b**m* (1<=β€<=*b**i*<=β€<=*n*) β important indices of the array.
Output Specification:
Print *m* numbers, *i*-th of which is equal to the number at index *b**i* after all queries are done.
Demo Input:
['6 3 5\n1 2 3 4 5 6\n2 1 3\n2 3 6\n1 1 6\n2 2 1 5 3\n']
Demo Output:
['3 3 1 5 2 \n']
Note:
none | 1,560 |
Title: Restoration of string
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.
You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes).
A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string.
The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.
String *a* is lexicographically smaller than string *b*, if *a* is a prefix of *b*, or *a* has a smaller letter at the first position where *a* and *b* differ.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=105)Β β the number of strings in the set.
Each of the next *n* lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct.
The total length of the strings doesn't exceed 105.
Output Specification:
Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings.
Demo Input:
['4\nmail\nai\nlru\ncf\n', '3\nkek\npreceq\ncheburek\n']
Demo Output:
['cfmailru\n', 'NO\n']
Note:
One can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum. | 1,561 |
Title: Planar Graph
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A graph is called planar, if it can be drawn in such a way that its edges intersect only at their vertexes.
An articulation point is such a vertex of an undirected graph, that when removed increases the number of connected components of the graph.
A bridge is such an edge of an undirected graph, that when removed increases the number of connected components of the graph.
You've got a connected undirected planar graph consisting of *n* vertexes, numbered from 1 to *n*, drawn on the plane. The graph has no bridges, articulation points, loops and multiple edges. You are also given *q* queries. Each query is a cycle in the graph. The query response is the number of graph vertexes, which (if you draw a graph and the cycle on the plane) are located either inside the cycle, or on it. Write a program that, given the graph and the queries, will answer each query.
Input Specification:
The first line contains two space-separated integers *n* and *m* (3<=β€<=*n*,<=*m*<=β€<=105) β the number of vertexes and edges of the graph. Next *m* lines contain the edges of the graph: the *i*-th line contains two space-separated integers *u**i* and *v**i* (1<=β€<=*u**i*,<=*v**i*<=β€<=*n*) β the numbers of vertexes, connecting the *i*-th edge. The next *n* lines contain the positions of the planar graph vertexes on the plane: the *i*-th line contains a pair of space-separated integers *x**i* and *y**i* (|*x**i*|,<=|*y**i*|<=β€<=109) β the coordinates of the *i*-th vertex of the graph on the plane.
The next line contains integer *q* (1<=β€<=*q*<=β€<=105)Β β the number of queries. Then follow *q* lines that describe the queries: the *i*-th line contains the sequence of space-separated integers *k**i*, *a*1, *a*2, ..., *a**k**i* (1<=β€<=*a**j*<=β€<=*n*;Β *k**i*<=><=2), where *k**i* is the cycle length in the *i*-th query, *a**j* are numbers of the vertexes that form a cycle. The numbers of vertexes in the cycle are given in the clockwise or counterclockwise order. The given cycles are simple, that is they cannot go through a graph vertex more than once. The total length of all cycles in all queries does not exceed 105.
It is guaranteed that the given graph contains no bridges, articulation points, loops and multiple edges. It is guaranteed that the edge segments can have common points only at the graph's vertexes.
Output Specification:
For each query print a single integer β the number of vertexes inside the cycle or on it. Print the answers in the order, in which the queries follow in the input. Separate the numbers by spaces.
Demo Input:
['3 3\n1 2\n2 3\n3 1\n0 0\n1 0\n0 1\n1\n3 1 2 3\n', '5 8\n1 2\n2 3\n3 4\n4 1\n1 5\n2 5\n3 5\n4 5\n0 0\n2 0\n2 2\n0 2\n1 1\n1\n4 1 2 3 4\n', '4 5\n1 2\n2 3\n3 4\n4 1\n2 4\n0 0\n1 0\n1 1\n0 1\n3\n3 1 2 4\n3 4 2 3\n4 1 2 3 4\n']
Demo Output:
['3\n', '5\n', '3\n3\n4\n']
Note:
none | 1,562 |
Title: LIS of Sequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.
Nam created a sequence *a* consisting of *n* (1<=β€<=*n*<=β€<=105) elements *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=105). A subsequence *a**i*1,<=*a**i*2,<=...,<=*a**i**k* where 1<=β€<=*i*1<=<<=*i*2<=<<=...<=<<=*i**k*<=β€<=*n* is called increasing if *a**i*1<=<<=*a**i*2<=<<=*a**i*3<=<<=...<=<<=*a**i**k*. An increasing subsequence is called longest if it has maximum length among all increasing subsequences.
Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes *i* (1<=β€<=*i*<=β€<=*n*), into three groups:
1. group of all *i* such that *a**i* belongs to no longest increasing subsequences.1. group of all *i* such that *a**i* belongs to at least one but not every longest increasing subsequence.1. group of all *i* such that *a**i* belongs to every longest increasing subsequence.
Since the number of longest increasing subsequences of *a* may be very large, categorizing process is very difficult. Your task is to help him finish this job.
Input Specification:
The first line contains the single integer *n* (1<=β€<=*n*<=β€<=105) denoting the number of elements of sequence *a*.
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=105).
Output Specification:
Print a string consisting of *n* characters. *i*-th character should be '1', '2' or '3' depending on which group among listed above index *i* belongs to.
Demo Input:
['1\n4\n', '4\n1 3 2 5\n', '4\n1 5 2 3\n']
Demo Output:
['3\n', '3223\n', '3133\n']
Note:
In the second sample, sequence *a* consists of 4 elements: {*a*<sub class="lower-index">1</sub>,β*a*<sub class="lower-index">2</sub>,β*a*<sub class="lower-index">3</sub>,β*a*<sub class="lower-index">4</sub>} = {1,β3,β2,β5}. Sequence *a* has exactly 2 longest increasing subsequences of length 3, they are {*a*<sub class="lower-index">1</sub>,β*a*<sub class="lower-index">2</sub>,β*a*<sub class="lower-index">4</sub>} = {1,β3,β5} and {*a*<sub class="lower-index">1</sub>,β*a*<sub class="lower-index">3</sub>,β*a*<sub class="lower-index">4</sub>} = {1,β2,β5}.
In the third sample, sequence *a* consists of 4 elements: {*a*<sub class="lower-index">1</sub>,β*a*<sub class="lower-index">2</sub>,β*a*<sub class="lower-index">3</sub>,β*a*<sub class="lower-index">4</sub>} = {1,β5,β2,β3}. Sequence *a* have exactly 1 longest increasing subsequence of length 3, that is {*a*<sub class="lower-index">1</sub>,β*a*<sub class="lower-index">3</sub>,β*a*<sub class="lower-index">4</sub>} = {1,β2,β3}. | 1,563 |
Title: Take-off Ramps
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya participates in a ski race along the *X* axis. The start is at point 0, and the finish is at *L*, that is, at a distance *L* meters from the start in the positive direction of the axis. Vasya has been training so hard that he can run one meter in exactly one second.
Besides, there are *n* take-off ramps on the track, each ramp is characterized by four numbers:
- *x**i* represents the ramp's coordinate - *d**i* represents from how many meters Vasya will land if he goes down this ramp - *t**i* represents the flight time in seconds - *p**i* is the number, indicating for how many meters Vasya should gather speed to get ready and fly off the ramp. As Vasya gathers speed, he should ski on the snow (that is, he should not be flying), but his speed still equals one meter per second.
Vasya is allowed to move in any direction on the *X* axis, but he is prohibited to cross the start line, that is go to the negative semiaxis. Vasya himself chooses which take-off ramps he will use and in what order, that is, he is not obliged to take off from all the ramps he encounters. Specifically, Vasya can skip the ramp. It is guaranteed that *x**i*<=+<=*d**i*<=β€<=*L*, that is, Vasya cannot cross the finish line in flight.
Vasya can jump from the ramp only in the positive direction of *X* axis. More formally, when using the *i*-th ramp, Vasya starts gathering speed at point *x**i*<=-<=*p**i*, jumps at point *x**i*, and lands at point *x**i*<=+<=*d**i*. He cannot use the ramp in opposite direction.
Your task is to find the minimum time that Vasya will spend to cover the distance.
Input Specification:
The first line contains two integers *n* and *L* (0<=β€<=*n*<=β€<=105, 1<=β€<=*L*<=β€<=109). Then *n* lines contain the descriptions of the ramps, each description is on a single line. Each description is a group of four non-negative integers *x**i*, *d**i*, *t**i*, *p**i* (0<=β€<=*x**i*<=β€<=*L*, 1<=β€<=*d**i*,<=*t**i*,<=*p**i*<=β€<=109, *x**i*<=+<=*d**i*<=β€<=*L*).
Output Specification:
Print in the first line the minimum time in seconds Vasya needs to complete the track. Print in the second line *k* β the number of take-off ramps that Vasya needs to use, and print on the third line of output *k* numbers the number the take-off ramps Vasya used in the order in which he used them. Print each number exactly once, separate the numbers with a space. The ramps are numbered starting from 1 in the order in which they are given in the input.
Demo Input:
['2 20\n5 10 5 5\n4 16 1 7\n', '2 20\n9 8 12 6\n15 5 1 1\n']
Demo Output:
['15\n1\n1 ', '16\n1\n2 ']
Note:
In the first sample, Vasya cannot use ramp 2, because then he will need to gather speed starting from point -3, which is not permitted by the statement. The optimal option is using ramp 1, the resulting time is: moving to the point of gathering speed + gathering speed until reaching the takeoff ramp + flight time + moving to the finish lineβ=β0β+β5β+β5β+β5β=β15.
In the second sample using ramp 1 is not optimal for Vasya as *t*<sub class="lower-index">1</sub>β>β*d*<sub class="lower-index">1</sub>. The optimal option is using ramp 2, the resulting time is: moving to the point of gathering speed + gathering speed until reaching the takeoff ramp + flight time + moving to the finish lineβ=β14β+β1β+β1β+β0β=β16. | 1,564 |
Title: Two out of Three
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem.
Let the queue to the cashier contain *n* people, at that each of them is characterized by a positive integer *a**i* β that is the time needed to work with this customer. What is special about this very cashier is that it can serve two customers simultaneously. However, if two customers need *a**i* and *a**j* of time to be served, the time needed to work with both of them customers is equal to *max*(*a**i*,<=*a**j*). Please note that working with customers is an uninterruptable process, and therefore, if two people simultaneously come to the cashier, it means that they begin to be served simultaneously, and will both finish simultaneously (it is possible that one of them will have to wait).
Vasya used in his algorithm an ingenious heuristic β as long as the queue has more than one person waiting, then some two people of the first three standing in front of the queue are sent simultaneously. If the queue has only one customer number *i*, then he goes to the cashier, and is served within *a**i* of time. Note that the total number of phases of serving a customer will always be equal to β*n*<=/<=2β.
Vasya thinks that this method will help to cope with the queues we all hate. That's why he asked you to work out a program that will determine the minimum time during which the whole queue will be served using this algorithm.
Input Specification:
The first line of the input file contains a single number *n* (1<=β€<=*n*<=β€<=1000), which is the number of people in the sequence. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=106). The people are numbered starting from the cashier to the end of the queue.
Output Specification:
Print on the first line a single number β the minimum time needed to process all *n* people. Then on β*n*<=/<=2β lines print the order in which customers will be served. Each line (probably, except for the last one) must contain two numbers separated by a space β the numbers of customers who will be served at the current stage of processing. If *n* is odd, then the last line must contain a single number β the number of the last served customer in the queue. The customers are numbered starting from 1.
Demo Input:
['4\n1 2 3 4\n', '5\n2 4 3 1 4\n']
Demo Output:
['6\n1 2\n3 4\n', '8\n1 3\n2 5\n4\n']
Note:
none | 1,565 |
Title: File Name
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.
Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".
You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string "exxxii", then the resulting string is "exxii".
Input Specification:
The first line contains integer $n$ $(3 \le n \le 100)$ β the length of the file name.
The second line contains a string of length $n$ consisting of lowercase Latin letters only β the file name.
Output Specification:
Print the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. If initially the file name dost not contain a forbidden substring "xxx", print 0.
Demo Input:
['6\nxxxiii\n', '5\nxxoxx\n', '10\nxxxxxxxxxx\n']
Demo Output:
['1\n', '0\n', '8\n']
Note:
In the first example Polycarp tried to send a file with name contains number $33$, written in Roman numerals. But he can not just send the file, because it name contains three letters "x" in a row. To send the file he needs to remove any one of this letters. | 1,566 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Hamed has recently found a string *t* and suddenly became quite fond of it. He spent several days trying to find all occurrences of *t* in other strings he had. Finally he became tired and started thinking about the following problem. Given a string *s* how many ways are there to extract *k*<=β₯<=1 non-overlapping substrings from it such that each of them contains string *t* as a substring? More formally, you need to calculate the number of ways to choose two sequences *a*1,<=*a*2,<=...,<=*a**k* and *b*1,<=*b*2,<=...,<=*b**k* satisfying the following requirements:
- *k*<=β₯<=1 - - - - Β Β *t* is a substring of string *s**a**i**s**a**i*<=+<=1... *s**b**i* (string *s* is considered as 1-indexed).
As the number of ways can be rather large print it modulo 109<=+<=7.
Input Specification:
Input consists of two lines containing strings *s* and *t* (1<=β€<=|*s*|,<=|*t*|<=β€<=105). Each string consists of lowercase Latin letters.
Output Specification:
Print the answer in a single line.
Demo Input:
['ababa\naba\n', 'welcometoroundtwohundredandeightytwo\nd\n', 'ddd\nd\n']
Demo Output:
['5\n', '274201\n', '12\n']
Note:
none | 1,567 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a sequence of n integers *a*1,<=*a*2,<=...,<=*a**n*.
Determine a real number *x* such that the weakness of the sequence *a*1<=-<=*x*,<=*a*2<=-<=*x*,<=...,<=*a**n*<=-<=*x* is as small as possible.
The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.
The poorness of a segment is defined as the absolute value of sum of the elements of segment.
Input Specification:
The first line contains one integer *n* (1<=β€<=*n*<=β€<=200<=000), the length of a sequence.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (|*a**i*|<=β€<=10<=000).
Output Specification:
Output a real number denoting the minimum possible weakness of *a*1<=-<=*x*,<=*a*2<=-<=*x*,<=...,<=*a**n*<=-<=*x*. Your answer will be considered correct if its relative or absolute error doesn't exceed 10<=-<=6.
Demo Input:
['3\n1 2 3\n', '4\n1 2 3 4\n', '10\n1 10 2 9 3 8 4 7 5 6\n']
Demo Output:
['1.000000000000000\n', '2.000000000000000\n', '4.500000000000000\n']
Note:
For the first case, the optimal value of *x* is 2 so the sequence becomes β-β1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case.
For the second sample the optimal value of *x* is 2.5 so the sequence becomes β-β1.5,ββ-β0.5,β0.5,β1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case. | 1,568 |
Title: Little Elephant and Triangle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Little Elephant is playing with the Cartesian coordinates' system. Most of all he likes playing with integer points. The Little Elephant defines an integer point as a pair of integers (*x*;Β *y*), such that 0<=β€<=*x*<=β€<=*w* and 0<=β€<=*y*<=β€<=*h*. Thus, the Little Elephant knows only (*w*<=+<=1)Β·(*h*<=+<=1) distinct integer points.
The Little Elephant wants to paint a triangle with vertexes at integer points, the triangle's area must be a positive integer. For that, he needs to find the number of groups of three points that form such triangle. At that, the order of points in a group matters, that is, the group of three points (0;0), (0;2), (2;2) isn't equal to the group (0;2), (0;0), (2;2).
Help the Little Elephant to find the number of groups of three integer points that form a nondegenerate triangle with integer area.
Input Specification:
A single line contains two integers *w* and *h* (1<=β€<=*w*,<=*h*<=β€<=4000).
Output Specification:
In a single output line print an integer β the remainder of dividing the answer to the problem by 1000000007 (109<=+<=7).
Demo Input:
['2 1\n', '2 2\n']
Demo Output:
['36\n', '240\n']
Note:
none | 1,569 |
Title: Hiking
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the *i*-th rest point the distance from the start equals *x**i*, and its picturesqueness equals *b**i*. The traveler will move down the river in one direction, we can assume that he will start from point 0 on the coordinate axis and rest points are points with coordinates *x**i*.
Every day the traveler wants to cover the distance *l*. In practice, it turns out that this is not always possible, because he needs to end each day at one of the resting points. In addition, the traveler is choosing between two desires: cover distance *l* every day and visit the most picturesque places.
Let's assume that if the traveler covers distance *r**j* in a day, then he feels frustration , and his total frustration over the hike is calculated as the total frustration on all days.
Help him plan the route so as to minimize the relative total frustration: the total frustration divided by the total picturesqueness of all the rest points he used.
The traveler's path must end in the farthest rest point.
Input Specification:
The first line of the input contains integers *n*,<=*l* (1<=β€<=*n*<=β€<=1000,<=1<=β€<=*l*<=β€<=105) β the number of rest points and the optimal length of one day path.
Then *n* lines follow, each line describes one rest point as a pair of integers *x**i*,<=*b**i* (1<=β€<=*x**i*,<=*b**i*<=β€<=106). No two rest points have the same *x**i*, the lines are given in the order of strictly increasing *x**i*.
Output Specification:
Print the traveler's path as a sequence of the numbers of the resting points he used in the order he used them. Number the points from 1 to *n* in the order of increasing *x**i*. The last printed number must be equal to *n*.
Demo Input:
['5 9\n10 10\n20 10\n30 1\n31 5\n40 10\n']
Demo Output:
['1 2 4 5 ']
Note:
In the sample test the minimum value of relative total frustration approximately equals 0.097549. This value can be calculated as <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bad16faba2aa8ac4e81ca909b5e927a7f644c23f.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | 1,570 |
Title: The Winds of Winter
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Given a rooted tree with *n* nodes. The Night King removes exactly one node from the tree and all the edges associated with it. Doing this splits the tree and forms a forest. The node which is removed is not a part of the forest.
The root of a tree in the forest is the node in that tree which does not have a parent. We define the strength of the forest as the size of largest tree in forest.
Jon Snow wants to minimize the strength of the forest. To do this he can perform the following operation at most once.
He removes the edge between a node and its parent and inserts a new edge between this node and any other node in forest such that the total number of trees in forest remain same.
For each node *v* you need to find the minimum value of strength of the forest formed when node *v* is removed.
Input Specification:
The first line of the input contains an integer *n* (1<=<=β€<=<=*n*<=<=β€<=<=105) β the number of vertices in the tree. Each of the next *n* lines contains a pair of vertex indices *u**i* and *v**i* (1<=<=β€<=<=*u**i*,<=<=*v**i*<=<=β€<=<=*n*) where *u**i* is the parent of *v**i*. If *u**i*<==<=0 then *v**i* is the root.
Output Specification:
Print *n* line each containing a single integer. The *i*-th of them should be equal to minimum value of strength of forest formed when *i*-th node is removed and Jon Snow performs the operation described above at most once.
Demo Input:
['10\n0 1\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n4 8\n4 9\n5 10\n', '2\n2 1\n0 2\n']
Demo Output:
['3\n4\n5\n5\n5\n9\n9\n9\n9\n9\n', '1\n1\n']
Note:
The tree for first test case is depicted below. <img class="tex-graphics" src="https://espresso.codeforces.com/11c39aaab54dce5e508a594b4f57109d5cc3b317.png" style="max-width: 100.0%;max-height: 100.0%;"/> When you remove the first node, the tree splits to form the following forest. The strength of this forest is 4. <img class="tex-graphics" src="https://espresso.codeforces.com/af8ff74e6630469b37f09c01be60d58b59cfabbd.png" style="max-width: 100.0%;max-height: 100.0%;"/> Jon Snow now changes the parent of vertex 10 from 5 to 3. The strength of forest now becomes 3. <img class="tex-graphics" src="https://espresso.codeforces.com/7c76b3c1797ba9a71a6f8086986b53ad566ff4ea.png" style="max-width: 100.0%;max-height: 100.0%;"/> | 1,571 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of *n* compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.
The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.
However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number.
After all the swaps each compartment should either have no student left, or have a company of three or four students.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=106) β the number of compartments in the carriage. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* showing how many students ride in each compartment (0<=β€<=*a**i*<=β€<=4). It is guaranteed that at least one student is riding in the train.
Output Specification:
If no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.
Demo Input:
['5\n1 2 2 4 3\n', '3\n4 1 1\n', '4\n0 3 0 4\n']
Demo Output:
['2\n', '2\n', '0\n']
Note:
none | 1,572 |
Title: Automatic Door
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is an automatic door at the entrance of a factory. The door works in the following way:
- when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside, - when one or several people come to the door and it is open, all people immediately come inside, - opened door immediately closes in *d* seconds after its opening, - if the door is closing and one or several people are coming to the door at the same moment, then all of them will have enough time to enter and only after that the door will close.
For example, if *d*<==<=3 and four people are coming at four different moments of time *t*1<==<=4, *t*2<==<=7, *t*3<==<=9 and *t*4<==<=13 then the door will open three times: at moments 4, 9 and 13. It will close at moments 7 and 12.
It is known that *n* employees will enter at moments *a*,<=2Β·*a*,<=3Β·*a*,<=...,<=*n*Β·*a* (the value *a* is positive integer). Also *m* clients will enter at moments *t*1,<=*t*2,<=...,<=*t**m*.
Write program to find the number of times the automatic door will open. Assume that the door is initially closed.
Input Specification:
The first line contains four integers *n*, *m*, *a* and *d* (1<=β€<=*n*,<=*a*<=β€<=109, 1<=β€<=*m*<=β€<=105, 1<=β€<=*d*<=β€<=1018) β the number of the employees, the number of the clients, the moment of time when the first employee will come and the period of time in which the door closes.
The second line contains integer sequence *t*1,<=*t*2,<=...,<=*t**m* (1<=β€<=*t**i*<=β€<=1018) β moments of time when clients will come. The values *t**i* are given in non-decreasing order.
Output Specification:
Print the number of times the door will open.
Demo Input:
['1 1 3 4\n7\n', '4 3 4 2\n7 9 11\n']
Demo Output:
['1\n', '4\n']
Note:
In the first example the only employee will come at moment 3. At this moment the door will open and will stay open until the moment 7. At the same moment of time the client will come, so at first he will enter and only after it the door will close. Thus the door will open one time. | 1,573 |
Title: Weak Subsequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to *k*. However, the voucher has a string type limitation: specifically, the voucher can be used to purchase string *s* if the length of string's longest substring that is also its weak subsequence (see the definition given below) equals *w*.
String *a* with the length of *n* is considered the weak subsequence of the string *s* with the length of *m*, if there exists such a set of indexes 1<=β€<=*i*1<=<<=*i*2<=<<=...<=<<=*i**n*<=β€<=*m*, that has the following two properties:
- *a**k*<==<=*s**i**k* for all *k* from 1 to *n*; - there exists at least one such *k* (1<=β€<=*k*<=<<=*n*), for which *i**k*<=+<=1<=β<=*i**k*<=><=1.
Petya got interested how many different strings are available for him to purchase in the shop. As the number of strings can be very large, please find it modulo 1000000007 (109<=+<=7). If there are infinitely many such strings, print "-1".
Input Specification:
The first line contains two integers *k* (1<=β€<=*k*<=β€<=106) and *w* (2<=β€<=*w*<=β€<=109) β the alphabet size and the required length of the maximum substring that also is the weak subsequence, correspondingly.
Output Specification:
Print a single number β the number of strings Petya can buy using the voucher, modulo 1000000007 (109<=+<=7). If there are infinitely many such strings, print "-1" (without the quotes).
Demo Input:
['2 2\n', '3 5\n', '2 139\n']
Demo Output:
['10\n', '1593\n', '717248223\n']
Note:
In the first sample Petya can buy the following strings: aaa, aab, abab, abb, abba, baa, baab, baba, bba, bbb. | 1,574 |
Title: Mashmokh and Water Tanks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mashmokh is playing a new game. In the beginning he has *k* liters of water and *p* coins. Additionally he has a rooted tree (an undirected connected acyclic graph) that consists of *m* vertices. Each vertex of the tree contains a water tank that is empty in the beginning.
The game begins with the fact that Mashmokh chooses some (no more than *k*) of these tanks (except the root) and pours into each of them exactly 1 liter of water. Then the following process is performed until there is no water remained in tanks.
- The process consists of several steps. - At the beginning of each step Mashmokh opens doors of all tanks. Then Mashmokh closes doors of some tanks (he is not allowed to close door of tank in the root) for the duration of this move. Let's denote the number of liters in some tank with closed door as *w*, Mashmokh pays *w* coins for the closing of that tank during this move. - Let's denote by *x*1,<=*x*2,<=...,<=*x**m* as the list of vertices of the tree sorted (nondecreasing) by their depth. The vertices from this list should be considered one by one in the order. Firstly vertex *x*1 (which is the root itself) is emptied. Then for each vertex *x**i* (*i*<=><=1), if its door is closed then skip the vertex else move all the water from the tank of vertex *x**i* to the tank of its father (even if the tank of the father is closed).
Suppose *l* moves were made until the tree became empty. Let's denote the amount of water inside the tank of the root after the *i*-th move by *w**i* then Mashmokh will win *max*(*w*1,<=*w*2,<=...,<=*w**l*) dollars. Mashmokh wanted to know what is the maximum amount of dollars he can win by playing the above game. He asked you to find this value for him.
Input Specification:
The first line of the input contains three space-separated integers *m*,<=*k*,<=*p*Β (2<=β€<=*m*<=β€<=105;Β 0<=β€<=*k*,<=*p*<=β€<=109).
Each of the following *m*<=-<=1 lines contains two space-separated integers *a**i*,<=*b**i*Β (1<=β€<=*a**i*,<=*b**i*<=β€<=*m*;Β *a**i*<=β <=*b**i*) β the edges of the tree.
Consider that the vertices of the tree are numbered from 1 to *m*. The root of the tree has number 1.
Output Specification:
Output a single integer, the number Mashmokh asked you to find.
Demo Input:
['10 2 1\n1 2\n1 3\n3 4\n3 5\n2 6\n6 8\n6 7\n9 8\n8 10\n', '5 1000 1000\n1 2\n1 3\n3 4\n3 5\n']
Demo Output:
['2\n', '4\n']
Note:
The tree in the first sample is shown on the picture below. The black, red, blue colors correspond to vertices with 0, 1, 2 liters of water.
One way to achieve the maximum amount of money is to put 1 liter of water in each of vertices 3 and 4. The beginning state is shown on the picture below.
Then in the first move Mashmokh will pay one token to close the door of the third vertex tank. The tree after the first move is shown on the picture below.
After the second move there are 2 liters of water in the root as shown on the picture below. | 1,575 |
Title: Lucky Numbers
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
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 Specification:
The only line contains a positive integer *n* (1<=β€<=*n*<=β€<=10100000). This number doesn't have leading zeroes.
Output Specification:
Output the least super lucky number that is more than or equal to *n*.
Demo Input:
['4500\n', '47\n']
Demo Output:
['4747\n', '47\n']
Note:
none | 1,576 |
Title: An abandoned sentiment from past
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed.
To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long time, but now Kaiki provides an opportunity.
Hitagi's sequence *a* has a length of *n*. Lost elements in it are denoted by zeros. Kaiki provides another sequence *b*, whose length *k* equals the number of lost elements in *a* (i.e. the number of zeros). Hitagi is to replace each zero in *a* with an element from *b* so that each element in *b* should be used exactly once. Hitagi knows, however, that, apart from 0, no integer occurs in *a* and *b* more than once in total.
If the resulting sequence is not an increasing sequence, then it has the power to recover Hitagi from the oddity. You are to determine whether this is possible, or Kaiki's sequence is just another fake. In other words, you should detect whether it is possible to replace each zero in *a* with an integer from *b* so that each integer from *b* is used exactly once, and the resulting sequence is not increasing.
Input Specification:
The first line of input contains two space-separated positive integers *n* (2<=β€<=*n*<=β€<=100) and *k* (1<=β€<=*k*<=β€<=*n*) β the lengths of sequence *a* and *b* respectively.
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=200) β Hitagi's broken sequence with exactly *k* zero elements.
The third line contains *k* space-separated integers *b*1,<=*b*2,<=...,<=*b**k* (1<=β€<=*b**i*<=β€<=200) β the elements to fill into Hitagi's sequence.
Input guarantees that apart from 0, no integer occurs in *a* and *b* more than once in total.
Output Specification:
Output "Yes" if it's possible to replace zeros in *a* with elements in *b* and make the resulting sequence not increasing, and "No" otherwise.
Demo Input:
['4 2\n11 0 0 14\n5 4\n', '6 1\n2 3 0 8 9 10\n5\n', '4 1\n8 94 0 4\n89\n', '7 7\n0 0 0 0 0 0 0\n1 2 3 4 5 6 7\n']
Demo Output:
['Yes\n', 'No\n', 'Yes\n', 'Yes\n']
Note:
In the first sample:
- Sequence *a* is 11,β0,β0,β14. - Two of the elements are lost, and the candidates in *b* are 5 and 4. - There are two possible resulting sequences: 11,β5,β4,β14 and 11,β4,β5,β14, both of which fulfill the requirements. Thus the answer is "Yes".
In the second sample, the only possible resulting sequence is 2,β3,β5,β8,β9,β10, which is an increasing sequence and therefore invalid. | 1,577 |
Title: Interactive Bulls and Cows (Easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java β call System.out.flush(), and in Pascal β flush(output).
Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.
On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.
Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers β the number of "bulls" and the number of "cows". A try can contain equal digits.
More formally, let's the secret string is *s* and the second player are trying to guess it with a string *x*. The number of "bulls" is a number of such positions *i* (1<=β€<=*i*<=β€<=4) where *s*[*i*]<==<=*x*[*i*]. The number of "cows" is a number of such digits *c* that *s* contains *c* in the position *i* (i.e. *s*[*i*]<==<=*c*), *x* contains *c*, but *x*[*i*]<=β <=*c*.
For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.
In this problem you are to guess the string *s* that the system has chosen. You only know that the chosen string consists of 4 distinct digits.
You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons β the program either guessed the number *x* or made an invalid action (for example, printed letters instead of digits).
Your program is allowed to do at most 50 queries.
You can hack solutions of other participants providing a 4-digit string containing distinct digits β the secret string.
Input Specification:
To read answers to the queries, the program must use the standard input.
The program will receive pairs of non-negative integers in the input, one pair per line. The first number in a pair is a number of bulls and the second one is a number of cows of the string *s* and the string *x**i* printed by your program. If the system response equals "4 0", then your solution should terminate.
The testing system will let your program read the *i*-th pair of integers from the input only after your program displays the corresponding system query in the output: prints value *x**i* in a single line and executes operation flush.
Output Specification:
The program must use the standard output to print queries.
Your program must output requests β 4-digit strings *x*1,<=*x*2,<=..., one per line. After the output of each line the program must execute flush operation. The program should read the answer to the query from the standard input.
Your program is allowed to do at most 50 queries.
Demo Input:
['0 1\n2 0\n1 1\n0 4\n2 1\n4 0\n']
Demo Output:
['8000\n0179\n3159\n3210\n0112\n0123']
Note:
The secret string *s* in the example is "0123". | 1,578 |
Title: Codeword
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The famous sculptor Cicasso is a Reberlandian spy!
These is breaking news in Berlandian papers today. And now the sculptor is hiding. This time you give the shelter to the maestro. You have a protected bunker and you provide it to your friend. You set the security system in such way that only you can open the bunker. To open it one should solve the problem which is hard for others but is simple for you.
Every day the bunker generates a codeword *s*. Every time someone wants to enter the bunker, integer *n* appears on the screen. As the answer one should enter another integer β the residue modulo 109<=+<=7 of the number of strings of length *n* that consist only of lowercase English letters and contain the string *s* as the subsequence.
The subsequence of string *a* is a string *b* that can be derived from the string *a* by removing some symbols from it (maybe none or all of them). In particular any string is the subsequence of itself. For example, the string "cfo" is the subsequence of the string "codeforces".
You haven't implemented the algorithm that calculates the correct answers yet and you should do that ASAP.
Input Specification:
The first line contains integer *m* (1<=β€<=*m*<=β€<=105) β the number of the events in the test case.
The second line contains nonempty string *s* β the string generated by the bunker for the current day.
The next *m* lines contain the description of the events. The description starts from integer *t* β the type of the event.
If *t*<==<=1 consider a new day has come and now a new string *s* is used. In that case the same line contains a new value of the string *s*.
If *t*<==<=2 integer *n* is given (1<=β€<=*n*<=β€<=105). This event means that it's needed to find the answer for the current string *s* and the value *n*.
The sum of lengths of all generated strings doesn't exceed 105. All of the given strings consist only of lowercase English letters.
Output Specification:
For each query of the type 2 print the answer modulo 109<=+<=7 on the separate line.
Demo Input:
['3\na\n2 2\n1 bc\n2 5\n']
Demo Output:
['51\n162626\n']
Note:
In the first event words of the form "a?" and "?a" are counted, where ? is an arbitrary symbol. There are 26 words of each of these types, but the word "aa" satisfies both patterns, so the answer is 51. | 1,579 |
Title: Genetic Engineering
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You will receive 3 points for solving this problem.
Manao is designing the genetic code for a new type of algae to efficiently produce fuel. Specifically, Manao is focusing on a stretch of DNA that encodes one protein. The stretch of DNA is represented by a string containing only the characters 'A', 'T', 'G' and 'C'.
Manao has determined that if the stretch of DNA contains a maximal sequence of consecutive identical nucleotides that is of even length, then the protein will be nonfunctional. For example, consider a protein described by DNA string "GTTAAAG". It contains four maximal sequences of consecutive identical nucleotides: "G", "TT", "AAA", and "G". The protein is nonfunctional because sequence "TT" has even length.
Manao is trying to obtain a functional protein from the protein he currently has. Manao can insert additional nucleotides into the DNA stretch. Each additional nucleotide is a character from the set {'A', 'T', 'G', 'C'}. Manao wants to determine the minimum number of insertions necessary to make the DNA encode a functional protein.
Input Specification:
The input consists of a single line, containing a string *s* of length *n* (1<=β€<=*n*<=β€<=100). Each character of *s* will be from the set {'A', 'T', 'G', 'C'}.
This problem doesn't have subproblems. You will get 3 points for the correct submission.
Output Specification:
The program should print on one line a single integer representing the minimum number of 'A', 'T', 'G', 'C' characters that are required to be inserted into the input string in order to make all runs of identical characters have odd length.
Demo Input:
['GTTAAAG\n', 'AACCAACCAAAAC\n']
Demo Output:
['1\n', '5\n']
Note:
In the first example, it is sufficient to insert a single nucleotide of any type between the two 'T's in the sequence to restore the functionality of the protein. | 1,580 |
Title: On Number of Decompositions into Multipliers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an integer *m* as a product of integers *a*1,<=*a*2,<=... *a**n* . Your task is to find the number of distinct decompositions of number *m* into the product of *n* ordered positive integers.
Decomposition into *n* products, given in the input, must also be considered in the answer. As the answer can be very large, print it modulo 1000000007 (109<=+<=7).
Input Specification:
The first line contains positive integer *n* (1<=β€<=*n*<=β€<=500). The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109).
Output Specification:
In a single line print a single number *k* β the number of distinct decompositions of number *m* into *n* ordered multipliers modulo 1000000007 (109<=+<=7).
Demo Input:
['1\n15\n', '3\n1 1 2\n', '2\n5 7\n']
Demo Output:
['1\n', '3\n', '4\n']
Note:
In the second sample, the get a decomposition of number 2, you need any one number out of three to equal 2, and the rest to equal 1.
In the third sample, the possible ways of decomposing into ordered multipliers are [7,5], [5,7], [1,35], [35,1].
A decomposition of positive integer *m* into *n* ordered multipliers is a cortege of positive integers *b*β=β{*b*<sub class="lower-index">1</sub>,β*b*<sub class="lower-index">2</sub>,β... *b*<sub class="lower-index">*n*</sub>} such that <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/607dd79be814c0a988453395ca6d82109b016083.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Two decompositions *b* and *c* are considered different, if there exists index *i* such that *b*<sub class="lower-index">*i*</sub>ββ β*c*<sub class="lower-index">*i*</sub>. | 1,581 |
Title: New Year and Three Musketeers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Do you know the story about the three musketeers? Anyway, you must help them now.
Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength *a*, Borthos strength *b*, and Caramis has strength *c*.
The year 2015 is almost over and there are still *n* criminals to be defeated. The *i*-th criminal has strength *t**i*. It's hard to defeat strong criminalsΒ β maybe musketeers will have to fight together to achieve it.
Richelimakieu will coordinate musketeers' actions. In each hour each musketeer can either do nothing or be assigned to one criminal. Two or three musketeers can be assigned to the same criminal and then their strengths are summed up. A criminal can be defeated in exactly one hour (also if two or three musketeers fight him). Richelimakieu can't allow the situation where a criminal has strength bigger than the sum of strengths of musketeers fighting himΒ β a criminal would win then!
In other words, there are three ways to defeat a criminal.
- A musketeer of the strength *x* in one hour can defeat a criminal of the strength not greater than *x*. So, for example Athos in one hour can defeat criminal *i* only if *t**i*<=β€<=*a*. - Two musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of strengths of these two musketeers. So, for example Athos and Caramis in one hour can defeat criminal *i* only if *t**i*<=β€<=*a*<=+<=*c*. Note that the third remaining musketeer can either do nothing or fight some other criminal. - Similarly, all three musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of musketeers' strengths, i.e. *t**i*<=β€<=*a*<=+<=*b*<=+<=*c*.
Richelimakieu doesn't want musketeers to fight during the New Year's Eve. Thus, he must coordinate their actions in order to minimize the number of hours till all criminals will be defeated.
Find the minimum number of hours to defeat all criminals. If musketeers can't defeat them all then print "-1" (without the quotes) instead.
Input Specification:
The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=200<=000)Β β the number of criminals.
The second line contains three integers *a*, *b* and *c* (1<=β€<=*a*,<=*b*,<=*c*<=β€<=108)Β β strengths of musketeers.
The third line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=β€<=*t**i*<=β€<=108)Β β strengths of criminals.
Output Specification:
Print one line with the answer.
If it's impossible to defeat all criminals, print "-1" (without the quotes). Otherwise, print the minimum number of hours the three musketeers will spend on defeating all criminals.
Demo Input:
['5\n10 20 30\n1 1 1 1 50\n', '5\n10 20 30\n1 1 1 1 51\n', '7\n30 20 10\n34 19 50 33 88 15 20\n', '6\n10 5 10\n10 9 5 25 20 5\n']
Demo Output:
['2\n', '3\n', '-1\n', '3\n']
Note:
In the first sample Athos has strength 10, Borthos 20, and Caramis 30. They can defeat all criminals in two hours:
- Borthos and Caramis should together fight a criminal with strength 50. In the same hour Athos can fight one of four criminals with strength 1. - There are three criminals left, each with strength 1. Each musketeer can fight one criminal in the second hour.
In the second sample all three musketeers must together fight a criminal with strength 51. It takes one hour. In the second hour they can fight separately, each with one criminal. In the third hour one criminal is left and any of musketeers can fight him. | 1,582 |
Title: Megacity
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with *n* other locations, the *i*-th one has coordinates (*x**i*, *y**i*) with the population of *k**i* people. You can widen the city boundaries to a circle of radius *r*. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius *r*, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input Specification:
The first line of the input contains two integers *n* and *s* (1<=β€<=*n*<=β€<=103; 1<=β€<=*s*<=<<=106) β the number of locatons around Tomsk city and the population of the city. Then *n* lines follow. The *i*-th line contains three integers β the *x**i* and *y**i* coordinate values of the *i*-th location and the number *k**i* of people in it (1<=β€<=*k**i*<=<<=106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0;Β 0).
Output Specification:
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10<=-<=6.
Demo Input:
['4 999998\n1 1 1\n2 2 1\n3 3 1\n2 -2 1\n', '4 999998\n1 1 2\n2 2 1\n3 3 1\n2 -2 1\n', '2 1\n1 1 999997\n2 2 1\n']
Demo Output:
['2.8284271\n', '1.4142136\n', '-1']
Note:
none | 1,583 |
Title: Name
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.
Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string *s*. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name *t*.
On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name *t* and lexicographically minimum at that.
The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string *p* of length *n* is lexicographically less than string *q* of length *m*, if one of the two statements is correct:
- *n*<=<<=*m*, and *p* is the beginning (prefix) of string *q* (for example, "aba" is less than string "abaa"), - *p*1<==<=*q*1, *p*2<==<=*q*2, ..., *p**k*<=-<=1<==<=*q**k*<=-<=1, *p**k*<=<<=*q**k* for some *k* (1<=β€<=*k*<=β€<=*min*(*n*,<=*m*)), here characters in strings are numbered starting from 1.
Write a program that, given string *s* and the heighbours' child's name *t* determines the string that is the result of permutation of letters in *s*. The string should be lexicographically strictly more than *t* and also, lexicographically minimum.
Input Specification:
The first line contains a non-empty string *s* (1<=β€<=|*s*|<=β€<=5000), where |*s*| is its length. The second line contains a non-empty string *t* (1<=β€<=|*t*|<=β€<=5000), where |*t*| is its length. Both strings consist of lowercase Latin letters.
Output Specification:
Print the sought name or -1 if it doesn't exist.
Demo Input:
['aad\naac\n', 'abad\nbob\n', 'abc\ndefg\n', 'czaaab\nabcdef\n']
Demo Output:
['aad\n', 'daab\n', '-1\n', 'abczaa\n']
Note:
In the first sample the given string *s* is the sought one, consequently, we do not need to change the letter order there. | 1,584 |
Title: Google Code Jam
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Many of you must be familiar with the Google Code Jam round rules. Let us remind you of some key moments that are crucial to solving this problem. During the round, the participants are suggested to solve several problems, each divided into two subproblems: an easy one with small limits (Small input), and a hard one with large limits (Large input). You can submit a solution for Large input only after you've solved the Small input for this problem. There are no other restrictions on the order of solving inputs. In particular, the participant can first solve the Small input, then switch to another problem, and then return to the Large input. Solving each input gives the participant some number of points (usually different for each problem). This takes into account only complete solutions that work correctly on all tests of the input. The participant gets the test result of a Small input right after he submits it, but the test result of a Large input are out only after the round's over. In the final results table the participants are sorted by non-increasing of received points. If the points are equal, the participants are sorted by ascending of time penalty. By the Google Code Jam rules the time penalty is the time when the last correct solution was submitted.
Vasya decided to check out a new tactics on another round. As soon as the round begins, the boy quickly read all the problems and accurately evaluated the time it takes to solve them. Specifically, for each one of the *n* problems Vasya knows five values:
- Solving the Small input of the *i*-th problem gives to the participant *scoreSmall**i* points, and solving the Large input gives *scoreLarge**i* more points. That is, the maximum number of points you can get for the *i*-th problem equals *scoreSmall**i*<=+<=*scoreLarge**i*.- Writing the solution for the Small input of the *i*-th problem takes exactly *timeSmall**i* minutes for Vasya. Improving this code and turning it into the solution of the Large input takes another *timeLarge**i* minutes.- Vasya's had much practice, so he solves all Small inputs from the first attempt. But it's not so easy with the Large input: there is the *probFail**i* probability that the solution to the Large input will turn out to be wrong at the end of the round. Please keep in mind that these solutions do not affect the participants' points and the time penalty.
A round lasts for *t* minutes. The time for reading problems and submitting solutions can be considered to equal zero. Vasya is allowed to submit a solution exactly at the moment when the round ends.
Vasya wants to choose a set of inputs and the order of their solution so as to make the expectation of the total received points maximum possible. If there are multiple ways to do this, he needs to minimize the expectation of the time penalty. Help Vasya to cope with this problem.
Input Specification:
The first line contains two integers *n* and *t* (1<=β€<=*n*<=β€<=1000,<=1<=β€<=*t*<=β€<=1560). Then follow *n* lines, each containing 5 numbers: *scoreSmall**i*,<=*scoreLarge**i*,<=*timeSmall**i*,<=*timeLarge**i*,<=*probFail**i* (1<=β€<=*scoreSmall**i*,<=*scoreLarge**i*<=β€<=109,<=1<=β€<=*timeSmall**i*,<=*timeLarge**i*<=β€<=1560,<=0<=β€<=*probFail**i*<=β€<=1).
*probFail**i* are real numbers, given with at most 6 digits after the decimal point. All other numbers in the input are integers.
Output Specification:
Print two real numbers β the maximum expectation of the total points and the corresponding minimum possible time penalty expectation. The answer will be considered correct if the absolute or relative error doesn't exceed 10<=-<=9.
Demo Input:
['3 40\n10 20 15 4 0.5\n4 100 21 1 0.99\n1 4 1 1 0.25\n', '1 1\n100000000 200000000 1 1 0\n']
Demo Output:
['24.0 18.875\n', '100000000 1\n']
Note:
In the first sample one of the optimal orders of solving problems is:
1. The Small input of the third problem. 1. The Small input of the first problem. 1. The Large input of the third problem. 1. The Large input of the first problem.
Note that if you solve the Small input of the second problem instead of two inputs of the third one, then total score expectation will be the same but the time penalty expectation will be worse (38). | 1,585 |
Title: A Colourful Prospect
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Firecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement.
Little Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve.
A wonder strikes Tommy. How many regions are formed by the circles on the sky? We consider the sky as a flat plane. A region is a connected part of the plane with positive area, whose bound consists of parts of bounds of the circles and is a curve or several curves without self-intersections, and that does not contain any curve other than its boundaries. Note that exactly one of the regions extends infinitely.
Input Specification:
The first line of input contains one integer *n* (1<=β€<=*n*<=β€<=3), denoting the number of circles.
The following *n* lines each contains three space-separated integers *x*, *y* and *r* (<=-<=10<=β€<=*x*,<=*y*<=β€<=10, 1<=β€<=*r*<=β€<=10), describing a circle whose center is (*x*,<=*y*) and the radius is *r*. No two circles have the same *x*, *y* and *r* at the same time.
Output Specification:
Print a single integerΒ β the number of regions on the plane.
Demo Input:
['3\n0 0 1\n2 0 1\n4 0 1\n', '3\n0 0 2\n3 0 2\n6 0 2\n', '3\n0 0 2\n2 0 2\n1 1 2\n']
Demo Output:
['4\n', '6\n', '8\n']
Note:
For the first example,
For the second example,
For the third example, | 1,586 |
Title: Innokenty and a Football League
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.
Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that:
1. the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", 1. or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB".
Apart from this, there is a rule that if for some club *x* the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club *x*. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.
Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=1000)Β β the number of clubs in the league.
Each of the next *n* lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.
Output Specification:
It it is not possible to choose short names and satisfy all constraints, print a single line "NO".
Otherwise, in the first line print "YES". Then print *n* lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input.
If there are multiple answers, print any of them.
Demo Input:
['2\nDINAMO BYTECITY\nFOOTBALL MOSCOW\n', '2\nDINAMO BYTECITY\nDINAMO BITECITY\n', '3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP\n', '3\nABC DEF\nABC EFG\nABD OOO\n']
Demo Output:
['YES\nDIN\nFOO\n', 'NO\n', 'YES\nPLM\nPLS\nGOG\n', 'YES\nABD\nABE\nABO\n']
Note:
In the first sample Innokenty can choose first option for both clubs.
In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.
In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.
In the fourth example note that it is possible that the chosen short name for some club *x* is the same as the first option of another club *y* if the first options of *x* and *y* are different. | 1,587 |
Title: Martian Colony
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The first ship with the Earth settlers landed on Mars. The colonists managed to build *n* necessary structures on the surface of the planet (which can be regarded as a plane, and the construction can be regarded as points on it). But one day the scanners recorded suspicious activity on the outskirts of the colony. It was decided to use the protective force field generating system to protect the colony against possible trouble.
The system works as follows: the surface contains a number of generators of the field (they can also be considered as points). The active range of each generator is a circle of radius *r* centered at the location of the generator (the boundary of the circle is also included in the range). After the system is activated, it stretches the protective force field only over the part of the surface, which is within the area of all generators' activity. That is, the protected part is the intersection of the generators' active ranges.
The number of generators available to the colonists is not limited, but the system of field generation consumes a lot of energy. More precisely, the energy consumption does not depend on the number of generators, but it is directly proportional to the area, which is protected by the field. Also, it is necessary that all the existing buildings are located within the protected area.
Determine the smallest possible area of the protected part of the surface containing all the buildings.
Input Specification:
The first line contains two integers *n* and *r* (1<=β€<=*n*<=β€<=105, 1<=β€<=*r*<=β€<=50000) β the number of buildings and the active ranges of the generators, correspondingly.
Next *n* lines contains the buildings' coordinates. The *i*<=+<=1-th (1<=β€<=*i*<=β€<=*n*) line contains two real numbers with at most three digits after the decimal point *x**i* and *y**i* (|*x**i*|,<=|*y**i*|<=β€<=50000) β coordinates of the *i*-th building. It is guaranteed that no two buildings are located at the same point, and no two different buildings are located closer than 1.
It is guaranteed that there exists a circle with radius *r* that contains all the buildings.
Output Specification:
Print the single real number β the minimum area of the protected part containing all the buildings. The answer is accepted if absolute or relative error doesn't exceed 10<=-<=4.
Demo Input:
['3 5\n0.00 0.000\n0.0 8.00\n6 8.00\n', '4 1000\n0.0 0.0\n0 2.00\n2.00 2\n2.0 0.00\n', '4 5\n3.00 0.0\n-3 0.00\n0.000 1\n0.0 -1.00\n']
Demo Output:
['78.5398163397\n', '4.0026666140\n', '8.1750554397\n']
Note:
In the first sample the given radius equals the radius of the circle circumscribed around the given points. That's why the circle that corresponds to it is the sought area. The answer is 25Ο.
In the second sample the area nearly coincides with the square which has vertexes in the given points.
The area for the third sample is shown on the picture below. | 1,588 |
Title: Little Frog
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are *n* mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.
Input Specification:
The single line contains a number *n* (1<=β€<=*n*<=β€<=104) which is the number of mounds.
Output Specification:
Print *n* integers *p**i* (1<=β€<=*p**i*<=β€<=*n*) which are the frog's route plan.
- All the *p**i*'s should be mutually different. - All the |*p**i*β*p**i*<=+<=1|'s should be mutually different (1<=β€<=*i*<=β€<=*n*<=-<=1).
If there are several solutions, output any.
Demo Input:
['2\n', '3\n']
Demo Output:
['1 2 ', '1 3 2 ']
Note:
none | 1,589 |
Title: Dasha and Stairs
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On her way to programming school tiger Dasha faced her first test β a huge staircase!
The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values β the number of steps with even and odd numbers.
You need to check whether there is an interval of steps from the *l*-th to the *r*-th (1<=β€<=*l*<=β€<=*r*), for which values that Dasha has found are correct.
Input Specification:
In the only line you are given two integers *a*, *b* (0<=β€<=*a*,<=*b*<=β€<=100) β the number of even and odd steps, accordingly.
Output Specification:
In the only line print "YES", if the interval of steps described above exists, and "NO" otherwise.
Demo Input:
['2 3\n', '3 1\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first example one of suitable intervals is from 1 to 5. The interval contains two even stepsΒ β 2 and 4, and three odd: 1, 3 and 5. | 1,590 |
Title: Game of Robots
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In late autumn evening *n* robots gathered in the cheerful company of friends. Each robot has a unique identifierΒ β an integer from 1 to 109.
At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the *n*-th robot says his identifier.
Your task is to determine the *k*-th identifier to be pronounced.
Input Specification:
The first line contains two positive integers *n* and *k* (1<=β€<=*n*<=β€<=100<=000, 1<=β€<=*k*<=β€<=*min*(2Β·109,<=*n*Β·(*n*<=+<=1)<=/<=2).
The second line contains the sequence *id*1,<=*id*2,<=...,<=*id**n* (1<=β€<=*id**i*<=β€<=109)Β β identifiers of roborts. It is guaranteed that all identifiers are different.
Output Specification:
Print the *k*-th pronounced identifier (assume that the numeration starts from 1).
Demo Input:
['2 2\n1 2\n', '4 5\n10 4 18 3\n']
Demo Output:
['1\n', '4\n']
Note:
In the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As *k*β=β2, the answer equals to 1.
In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As *k*β=β5, the answer equals to 4. | 1,591 |
Title: Turing Tape
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing *i*-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The *i*-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the *i*-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input Specification:
The input will consist of a single line *text* which contains the message printed using the described method. String *text* will contain between 1 and 100 characters, inclusive. ASCII-code of each character of *text* will be between 32 (space) and 126 (tilde), inclusive.
Output Specification:
Output the initial array, which was used to produce *text*, one integer per line.
Demo Input:
['Hello, World!\n']
Demo Output:
['238\n108\n112\n0\n64\n194\n48\n26\n244\n168\n24\n16\n162\n']
Note:
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72β=β01001000<sub class="lower-index">2</sub>. Its reverse is 00010010<sub class="lower-index">2</sub>β=β18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0β-β18) mod 256β=β238, where *a* mod *b* is the remainder of division of *a* by *b*. | 1,592 |
Title: Vasya and Robot
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has *n* items lying in a line. The items are consecutively numbered by numbers from 1 to *n* in such a way that the leftmost item has number 1, the rightmost item has number *n*. Each item has a weight, the *i*-th item weights *w**i* kilograms.
Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms β the left one and the right one. The robot can consecutively perform the following actions:
1. Take the leftmost item with the left hand and spend *w**i*<=Β·<=*l* energy units (*w**i* is a weight of the leftmost item, *l* is some parameter). If the previous action was the same (left-hand), then the robot spends extra *Q**l* energy units; 1. Take the rightmost item with the right hand and spend *w**j*<=Β·<=*r* energy units (*w**j* is a weight of the rightmost item, *r* is some parameter). If the previous action was the same (right-hand), then the robot spends extra *Q**r* energy units;
Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.
Input Specification:
The first line contains five integers *n*,<=*l*,<=*r*,<=*Q**l*,<=*Q**r* (1<=β€<=*n*<=β€<=105;<=1<=β€<=*l*,<=*r*<=β€<=100;<=1<=β€<=*Q**l*,<=*Q**r*<=β€<=104).
The second line contains *n* integers *w*1,<=*w*2,<=...,<=*w**n* (1<=β€<=*w**i*<=β€<=100).
Output Specification:
In the single line print a single number β the answer to the problem.
Demo Input:
['3 4 4 19 1\n42 3 99\n', '4 7 2 3 9\n1 2 3 4\n']
Demo Output:
['576\n', '34\n']
Note:
Consider the first sample. As *l*β=β*r*, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4Β·42β+β4Β·99β+β4Β·3β=β576 energy units.
The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2Β·4)β+β(7Β·1)β+β(2Β·3)β+β(2Β·2β+β9)β=β34 energy units. | 1,593 |
Title: Sereja and Subsequences
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sereja has a sequence that consists of *n* positive integers, *a*1,<=*a*2,<=...,<=*a**n*.
First Sereja took a piece of squared paper and wrote all distinct non-empty non-decreasing subsequences of sequence *a*. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all sequences that do not exceed it.
A sequence of positive integers *x*<==<=*x*1,<=*x*2,<=...,<=*x**r* doesn't exceed a sequence of positive integers *y*<==<=*y*1,<=*y*2,<=...,<=*y**r*, if the following inequation holds: *x*1<=β€<=*y*1,<=*x*2<=β€<=*y*2,<=...,<=*x**r*<=β€<=*y**r*.
Now Sereja wonders, how many sequences are written on the lines piece of paper. Help Sereja, find the required quantity modulo 1000000007 (109<=+<=7).
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=106).
Output Specification:
In the single line print the answer to the problem modulo 1000000007 (109<=+<=7).
Demo Input:
['1\n42\n', '3\n1 2 2\n', '5\n1 2 3 4 5\n']
Demo Output:
['42\n', '13\n', '719\n']
Note:
none | 1,594 |
Title: Sum the Fibonacci
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *s* of *n* non-negative integers.
A 5-tuple of integers (*a*,<=*b*,<=*c*,<=*d*,<=*e*) is said to be valid if it satisfies the following conditions:
- 1<=β€<=*a*,<=*b*,<=*c*,<=*d*,<=*e*<=β€<=*n* - (*s**a* | *s**b*) & *s**c* & (*s**d* ^ *s**e*)<==<=2*i* for some integer *i* - *s**a* & *s**b*<==<=0
Here, '|' is the bitwise OR, '&' is the bitwise AND and '^' is the bitwise XOR operation.
Find the sum of *f*(*s**a*|*s**b*)<=*<=*f*(*s**c*)<=*<=*f*(*s**d*^*s**e*) over all valid 5-tuples (*a*,<=*b*,<=*c*,<=*d*,<=*e*), where *f*(*i*) is the *i*-th Fibonnaci number (*f*(0)<==<=0,<=*f*(1)<==<=1,<=*f*(*i*)<==<=*f*(*i*<=-<=1)<=+<=*f*(*i*<=-<=2)).
Since answer can be is huge output it modulo 109<=+<=7.
Input Specification:
The first line of input contains an integer *n* (1<=β€<=*n*<=β€<=106).
The second line of input contains *n* integers *s**i* (0<=β€<=*s**i*<=<<=217).
Output Specification:
Output the sum as described above, modulo 109<=+<=7
Demo Input:
['2\n1 2\n', '3\n7 4 1\n', '10\n1 3 0 7 3 7 6 5 7 5\n', '10\n50 9 11 44 39 40 5 39 23 7\n']
Demo Output:
['32\n', '3520\n', '1235424\n', '113860062\n']
Note:
none | 1,595 |
Title: Labyrinth-14
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
See the problem statement here: [http://codeforces.com/contest/921/problem/01](//codeforces.com/contest/921/problem/01).
Input Specification:
none
Output Specification:
none
Note:
none | 1,596 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of *n* positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter *k*, so now his function contains the following code:
That way the function iteratively checks array elements, storing the intermediate maximum, and if after *k* consecutive iterations that maximum has not changed, it is returned as the answer.
Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to *n* such that the return value of his function on those permutations is not equal to *n*. Since this number could be very big, output the answer modulo 109<=+<=7.
Input Specification:
The only line contains two integers *n* and *k* (1<=β€<=*n*,<=*k*<=β€<=106), separated by a spaceΒ β the length of the permutations and the parameter *k*.
Output Specification:
Output the answer to the problem modulo 109<=+<=7.
Demo Input:
['5 2\n', '5 3\n', '6 3\n']
Demo Output:
['22\n', '6\n', '84\n']
Note:
Permutations from second example:
[4,β1,β2,β3,β5], [4,β1,β3,β2,β5], [4,β2,β1,β3,β5], [4,β2,β3,β1,β5], [4,β3,β1,β2,β5], [4,β3,β2,β1,β5]. | 1,597 |
Title: The Artful Expedient
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Rock... Paper!
After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.
A positive integer *n* is decided first. Both Koyomi and Karen independently choose *n* distinct positive integers, denoted by *x*1,<=*x*2,<=...,<=*x**n* and *y*1,<=*y*2,<=...,<=*y**n* respectively. They reveal their sequences, and repeat until all of 2*n* integers become distinct, which is the only final state to be kept and considered.
Then they count the number of ordered pairs (*i*,<=*j*) (1<=β€<=*i*,<=*j*<=β€<=*n*) such that the value *x**i* xor *y**j* equals to one of the 2*n* integers. Here xor means the [bitwise exclusive or](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.
Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.
Input Specification:
The first line of input contains a positive integer *n* (1<=β€<=*n*<=β€<=2<=000) β the length of both sequences.
The second line contains *n* space-separated integers *x*1,<=*x*2,<=...,<=*x**n* (1<=β€<=*x**i*<=β€<=2Β·106) β the integers finally chosen by Koyomi.
The third line contains *n* space-separated integers *y*1,<=*y*2,<=...,<=*y**n* (1<=β€<=*y**i*<=β€<=2Β·106) β the integers finally chosen by Karen.
Input guarantees that the given 2*n* integers are pairwise distinct, that is, no pair (*i*,<=*j*) (1<=β€<=*i*,<=*j*<=β€<=*n*) exists such that one of the following holds: *x**i*<==<=*y**j*; *i*<=β <=*j* and *x**i*<==<=*x**j*; *i*<=β <=*j* and *y**i*<==<=*y**j*.
Output Specification:
Output one line β the name of the winner, that is, "Koyomi" or "Karen" (without quotes). Please be aware of the capitalization.
Demo Input:
['3\n1 2 3\n4 5 6\n', '5\n2 4 6 8 10\n9 7 5 3 1\n']
Demo Output:
['Karen\n', 'Karen\n']
Note:
In the first example, there are 6 pairs satisfying the constraint: (1,β1), (1,β2), (2,β1), (2,β3), (3,β2) and (3,β3). Thus, Karen wins since 6 is an even number.
In the second example, there are 16 such pairs, and Karen wins again. | 1,598 |
Title: Lucky Transformation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
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 *d**x*<==<=4 and *d**x*<=+<=1<==<=7, if *x* is odd, then to assign *d**x*<==<=*d**x*<=+<=1<==<=4, otherwise to assign *d**x*<==<=*d**x*<=+<=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 Specification:
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 *d*1. It is guaranteed that the first digit of the number does not equal zero.
Output Specification:
In the single line print the result without spaces β the number after the *k* operations are fulfilled.
Demo Input:
['7 4\n4727447\n', '4 2\n4478\n']
Demo Output:
['4427477\n', '4478\n']
Note:
In the first sample the number changes in the following sequence: 4727447βββ4427447βββ4427477βββ4427447βββ4427477.
In the second sample: 4478βββ4778βββ4478. | 1,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.