task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Title: New Year and Cake
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Limak is a little polar bear. According to some old traditions, his bear family prepared a New Year cake. And Limak likes cakes.
As you may know, a New Year cake is a strictly convex polygon with *n* vertices.
Parents won't allow Limak to eat more than half of a cake because he would get sick. After some thinking they decided to cut a cake along one of *n*Β·(*n*<=-<=3)<=/<=2 diagonals. Then Limak will get a non-greater piece.
Limak understands rules but he won't be happy if the second piece happens to be much bigger. Limak's disappointment will be equal to the difference between pieces' areas, multiplied by two. It can be proved that it will be integer for the given constraints.
There are *n*Β·(*n*<=-<=3)<=/<=2 possible scenarios. Consider them all and find the sum of values of Limak's disappointment, modulo 109<=+<=7.
Input Specification:
The first line of the input contains a single integer *n* (4<=β€<=*n*<=β€<=500<=000)Β β the number of vertices in the polygon denoting the cake.
Each of the next *n* lines contains two integers *x**i* and *y**i* (|*x**i*|,<=|*y**i*|<=β€<=109)Β β coordinates of the *i*-th point.
It's guaranteed that all points are distinct, polygon is strictly convex and points are given in the clockwise order.
Output Specification:
Print the sum of values of Limak's disappointment over all possible scenarios modulo 109<=+<=7.
Demo Input:
['5\n2 4\n2 7\n5 7\n5 4\n3 -2\n', '4\n-1000000000 -5000000\n0 1234567\n1 1\n-5 -100000000\n', '8\n-10 0\n-6 6\n0 10\n6 6\n10 0\n6 -6\n0 -10\n-6 -6\n']
Demo Output:
['90\n', '525185196\n', '5216\n']
Note:
In the first sample possible values of Limak's disappointment are 0,β18,β18,β24,β30. | 1,400 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply).
As the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: "If the squared distance between some two soldiers equals to 5, then those soldiers will conflict with each other!"
The drill exercises are held on a rectangular *n*<=Γ<=*m* field, split into *nm* square 1<=Γ<=1 segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares (*x*1,<=*y*1) and (*x*2,<=*y*2) equals exactly (*x*1<=-<=*x*2)2<=+<=(*y*1<=-<=*y*2)2. Now not all *nm* squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square (2,<=2), then he cannot put soldiers in the squares (1,<=4), (3,<=4), (4,<=1) and (4,<=3) β each of them will conflict with the soldier in the square (2,<=2).
Your task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse.
Input Specification:
The single line contains space-separated integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=1000) that represent the size of the drill exercise field.
Output Specification:
Print the desired maximum number of warriors.
Demo Input:
['2 4\n', '3 4\n']
Demo Output:
['4', '6']
Note:
In the first sample test Sir Lancelot can place his 4 soldiers on the 2βΓβ4 court as follows (the soldiers' locations are marked with gray circles on the scheme):
In the second sample test he can place 6 soldiers on the 3βΓβ4 site in the following manner: | 1,401 |
Title: Robot Sequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of *n* commands, each either 'U', 'R', 'D', or 'L'Β β instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
Input Specification:
The first line of the input contains a single positive integer, *n* (1<=β€<=*n*<=β€<=200)Β β the number of commands.
The next line contains *n* characters, each either 'U', 'R', 'D', or 'L'Β β Calvin's source code.
Output Specification:
Print a single integerΒ β the number of contiguous substrings that Calvin can execute and return to his starting square.
Demo Input:
['6\nURLLDR\n', '4\nDLUU\n', '7\nRLRLRLR\n']
Demo Output:
['2\n', '0\n', '12\n']
Note:
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. | 1,402 |
Title: Game on Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Momiji has got a rooted tree, consisting of *n* nodes. The tree nodes are numbered by integers from 1 to *n*. The root has number 1. Momiji decided to play a game on this tree.
The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by *v*) and removes all the subtree nodes with the root in node *v* from the tree. Node *v* gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.
Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=105) β the number of nodes in the tree. The next *n*<=-<=1 lines contain the tree edges. The *i*-th line contains integers *a**i*, *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*;Β *a**i*<=β <=*b**i*) β the numbers of the nodes that are connected by the *i*-th edge.
It is guaranteed that the given graph is a tree.
Output Specification:
Print a single real number β the expectation of the number of steps in the described game.
The answer will be considered correct if the absolute or relative error doesn't exceed 10<=-<=6.
Demo Input:
['2\n1 2\n', '3\n1 2\n1 3\n']
Demo Output:
['1.50000000000000000000\n', '2.00000000000000000000\n']
Note:
In the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are:
In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: | 1,403 |
Title: Perishable Roads
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the country of Never, there are *n* cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered by Neverians.
An independent committee has evaluated each road of Never with a positive integer called the perishability of the road. The lower the road's perishability is, the more pleasant it is to drive through this road.
It's the year of transport in Never. It has been decided to build a museum of transport in one of the cities, and to set a single signpost directing to some city (not necessarily the one with the museum) in each of the other cities. The signposts must satisfy the following important condition: if any Neverian living in a city without the museum starts travelling from that city following the directions of the signposts, then this person will eventually arrive in the city with the museum.
Neverians are incredibly positive-minded. If a Neverian travels by a route consisting of several roads, he considers the perishability of the route to be equal to the smallest perishability of all the roads in this route.
The government of Never has not yet decided where to build the museum, so they consider all *n* possible options. The most important is the sum of perishabilities of the routes to the museum city from all the other cities of Never, if the travelers strictly follow the directions of the signposts. The government of Never cares about their citizens, so they want to set the signposts in a way which minimizes this sum. Help them determine the minimum possible sum for all *n* possible options of the city where the museum can be built.
Input Specification:
The first line contains a single integer *n* (2<=β€<=*n*<=β€<=2000)Β β the number of cities in Never.
The following *n*<=-<=1 lines contain the description of the road network. The *i*-th of these lines contains *n*<=-<=*i* integers. The *j*-th integer in the *i*-th line denotes the perishability of the road between cities *i* and *i*<=+<=*j*.
All road perishabilities are between 1 and 109, inclusive.
Output Specification:
For each city in order from 1 to *n*, output the minimum possible sum of perishabilities of the routes to this city from all the other cities of Never if the signposts are set in a way which minimizes this sum.
Demo Input:
['3\n1 2\n3\n', '6\n2 9 9 6 6\n7 1 9 10\n9 2 5\n4 10\n8\n']
Demo Output:
['2\n2\n3\n', '6\n5\n7\n5\n7\n11\n']
Note:
The first example is explained by the picture below. From left to right, there is the initial road network and the optimal directions of the signposts in case the museum is built in city 1, 2 and 3, respectively. The museum city is represented by a blue circle, the directions of the signposts are represented by green arrows.
For instance, if the museum is built in city 3, then the signpost in city 1 must be directed to city 3, while the signpost in city 2 must be directed to city 1. Then the route from city 1 to city 3 will have perishability 2, while the route from city 2 to city 3 will have perishability 1. The sum of perishabilities of these routes is 3. | 1,404 |
Title: Mike and Cellphone
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:
Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":
Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
Input Specification:
The first line of the input contains the only integer *n* (1<=β€<=*n*<=β€<=9)Β β the number of digits in the phone number that Mike put in.
The second line contains the string consisting of *n* digits (characters from '0' to '9') representing the number that Mike put in.
Output Specification:
If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.
Otherwise print "NO" (without quotes) in the first line.
Demo Input:
['3\n586\n', '2\n09\n', '9\n123456789\n', '3\n911\n']
Demo Output:
['NO\n', 'NO\n', 'YES\n', 'YES\n']
Note:
You can find the picture clarifying the first sample case in the statement above. | 1,405 |
Title: Cactus to Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a special connected undirected graph where each vertex belongs to at most one simple cycle.
Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles).
For each node, independently, output the maximum distance between it and a leaf in the resulting tree, assuming you were to remove the edges in a way that minimizes this distance.
Input Specification:
The first line of input contains two integers $n$ and $m$ ($1 \leq n \leq 5\cdot 10^5$), the number of nodes and the number of edges, respectively.
Each of the following $m$ lines contains two integers $u$ and $v$ ($1 \leq u,v \leq n$, $u \ne v$), and represents an edge connecting the two nodes $u$ and $v$. Each pair of nodes is connected by at most one edge.
It is guaranteed that the given graph is connected and each vertex belongs to at most one simple cycle.
Output Specification:
Print $n$ space-separated integers, the $i$-th integer represents the maximum distance between node $i$ and a leaf if the removed edges were chosen in a way that minimizes this distance.
Demo Input:
['9 10\n7 2\n9 2\n1 6\n3 1\n4 3\n4 7\n7 6\n9 8\n5 8\n5 9\n', '4 4\n1 2\n2 3\n3 4\n4 1\n']
Demo Output:
['5 3 5 4 5 4 3 5 4\n', '2 2 2 2\n']
Note:
In the first sample, a possible way to minimize the maximum distance from vertex $1$ is by removing the marked edges in the following image:
Note that to minimize the answer for different nodes, you can remove different edges. | 1,406 |
Title: Runaway to a Shadow
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dima is living in a dormitory, as well as some cockroaches.
At the moment 0 Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly *T* seconds for aiming, and after that he will precisely strike the cockroach and finish it.
To survive the cockroach has to run into a shadow, cast by round plates standing on the table, in *T* seconds. Shadow casted by any of the plates has the shape of a circle. Shadow circles may intersect, nest or overlap arbitrarily.
The cockroach uses the following strategy: first he equiprobably picks a direction to run towards and then runs towards it with the constant speed *v*. If at some moment *t*<=β€<=*T* it reaches any shadow circle, it immediately stops in the shadow and thus will stay alive. Otherwise the cockroach is killed by the Dima's precise strike. Consider that the Dima's precise strike is instant.
Determine the probability of that the cockroach will stay alive.
Input Specification:
In the first line of the input the four integers *x*0, *y*0, *v*, *T* (|*x*0|,<=|*y*0|<=β€<=109, 0<=β€<=*v*,<=*T*<=β€<=109) are givenΒ β the cockroach initial position on the table in the Cartesian system at the moment 0, the cockroach's constant speed and the time in seconds Dima needs for aiming respectively.
In the next line the only number *n* (1<=β€<=*n*<=β€<=100<=000) is givenΒ β the number of shadow circles casted by plates.
In the next *n* lines shadow circle description is given: the *i**th* of them consists of three integers *x**i*, *y**i*, *r**i* (|*x**i*|,<=|*y**i*|<=β€<=109, 0<=β€<=*r*<=β€<=109)Β β the *i**th* shadow circle on-table position in the Cartesian system and its radius respectively.
Consider that the table is big enough for the cockroach not to run to the table edges and avoid Dima's precise strike.
Output Specification:
Print the only real number *p*Β β the probability of that the cockroach will stay alive.
Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=4.
Demo Input:
['0 0 1 1\n3\n1 1 1\n-1 -1 1\n-2 2 1\n', '0 0 1 0\n1\n1 0 1\n']
Demo Output:
['0.50000000000', '1.00000000000']
Note:
The picture for the first sample is given below.
Red color stands for points which being chosen as the cockroach's running direction will cause him being killed, green color for those standing for survival directions. Please note that despite containing a circle centered in (β-β2,β2) a part of zone is colored red because the cockroach is not able to reach it in one second. | 1,407 |
Title: Which floor?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.
Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.
Given this information, is it possible to restore the exact floor for flat *n*?
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*<=β€<=100, 0<=β€<=*m*<=β€<=100), where *n* is the number of the flat you need to restore floor for, and *m* is the number of flats in Polycarp's memory.
*m* lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers *k**i*,<=*f**i* (1<=β€<=*k**i*<=β€<=100, 1<=β€<=*f**i*<=β€<=100), which means that the flat *k**i* is on the *f**i*-th floor. All values *k**i* are distinct.
It is guaranteed that the given information is not self-contradictory.
Output Specification:
Print the number of the floor in which the *n*-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.
Demo Input:
['10 3\n6 2\n2 1\n7 3\n', '8 4\n3 1\n6 2\n5 2\n2 1\n']
Demo Output:
['4\n', '-1\n']
Note:
In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.
In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat. | 1,408 |
Title: Appleman and a Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Appleman and Toastman like games. Today they play a game with strings with the following rules. Firstly Toastman tells Appleman two strings *s* and *t* both consisting only of letters 'A', 'B', 'C', 'D'. Then Appleman must build string *s* as quickly as possible. Initially he has empty string, and in one second he can append to end of the current string any contiguous substring of *t*.
Now, Toastman and Appleman are beginning to play the game. Toastman has already told string *t* to Appleman, but he hasn't come up with string *s* yet. Toastman only thinks, that he should choose string *s* consisting of *n* characters. Of course, he wants to find the worst string for Appleman (such string, that Appleman will spend as much time as possible during the game). Tell Toastman, how much time will Appleman spend during the game if Toastman finds the worst string for him. You can assume that Appleman plays optimally, therefore he builds any string *s* in minimal possible time.
Input Specification:
The first line contains an integer *n* (1<=β€<=*n*<=β€<=1018). The second line contains string *t* (1<=β€<=|*t*|<=β€<=105). String *t* consists of only letters 'A', 'B', 'C', 'D'. Each letter appears at least once in string *t*.
Output Specification:
Print a single integer β the largest possible time Appleman needs.
Demo Input:
['5\nABCCAD\n', '5\nAAABACADBABBBCBDCACBCCCDDDBDCDD\n']
Demo Output:
['5\n', '4\n']
Note:
In the first example, Toastman can choose *s* equal to "AAAAA".
In the second example, Toastman can choose *s* equal to "DADDA". | 1,409 |
Title: Subway
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A subway scheme, classic for all Berland cities is represented by a set of *n* stations connected by *n* passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.
Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.
This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).
The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.
Input Specification:
The first line contains an integer *n* (3<=β€<=*n*<=β€<=3000), *n* is the number of stations (and trains at the same time) in the subway scheme. Then *n* lines contain descriptions of the trains, one per line. Each line contains a pair of integers *x**i*,<=*y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=*n*) and represents the presence of a passage from station *x**i* to station *y**i*. The stations are numbered from 1 to *n* in an arbitrary order. It is guaranteed that *x**i*<=β <=*y**i* and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme.
Output Specification:
Print *n* numbers. Separate the numbers by spaces, the *i*-th one should be equal to the distance of the *i*-th station from the ringroad. For the ringroad stations print number 0.
Demo Input:
['4\n1 3\n4 3\n4 2\n1 2\n', '6\n1 2\n3 4\n6 4\n2 3\n1 3\n3 5\n']
Demo Output:
['0 0 0 0 ', '0 0 0 1 1 2 ']
Note:
none | 1,410 |
Title: Mashmokh and Tokens
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bimokh is Mashmokh's boss. For the following *n* days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back *w* tokens then he'll get dollars.
Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has *n* numbers *x*1,<=*x*2,<=...,<=*x**n*. Number *x**i* is the number of tokens given to each worker on the *i*-th day. Help him calculate for each of *n* days the number of tokens he can save.
Input Specification:
The first line of input contains three space-separated integers *n*,<=*a*,<=*b*Β (1<=β€<=*n*<=β€<=105;Β 1<=β€<=*a*,<=*b*<=β€<=109). The second line of input contains *n* space-separated integers *x*1,<=*x*2,<=...,<=*x**n*Β (1<=β€<=*x**i*<=β€<=109).
Output Specification:
Output *n* space-separated integers. The *i*-th of them is the number of tokens Mashmokh can save on the *i*-th day.
Demo Input:
['5 1 4\n12 6 11 9 1\n', '3 1 2\n1 2 3\n', '1 1 1\n1\n']
Demo Output:
['0 2 3 1 1 ', '1 0 1 ', '0 ']
Note:
none | 1,411 |
Title: Vladik and flights
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.
Vladik knows *n* airports. All the airports are located on a straight line. Each airport has unique id from 1 to *n*, Vladik's house is situated next to the airport with id *a*, and the place of the olympiad is situated next to the airport with id *b*. It is possible that Vladik's house and the place of the olympiad are located near the same airport.
To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport *a* and finish it at the airport *b*.
Each airport belongs to one of two companies. The cost of flight from the airport *i* to the airport *j* is zero if both airports belong to the same company, and |*i*<=-<=*j*| if they belong to different companies.
Print the minimum cost Vladik has to pay to get to the olympiad.
Input Specification:
The first line contains three integers *n*, *a*, and *b* (1<=β€<=*n*<=β€<=105, 1<=β€<=*a*,<=*b*<=β€<=*n*)Β β the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach.
The second line contains a string with length *n*, which consists only of characters 0 and 1. If the *i*-th character in this string is 0, then *i*-th airport belongs to first company, otherwise it belongs to the second.
Output Specification:
Print single integerΒ β the minimum cost Vladik has to pay to get to the olympiad.
Demo Input:
['4 1 4\n1010\n', '5 5 2\n10110\n']
Demo Output:
['1', '0']
Note:
In the first example Vladik can fly to the airport 2 at first and pay |1β-β2|β=β1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1.
In the second example Vladik can fly directly from the airport 5 to the airport 2, because they belong to the same company. | 1,412 |
Title: Not Wool Sequences
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A sequence of non-negative integers *a*1,<=*a*2,<=...,<=*a**n* of length *n* is called a wool sequence if and only if there exists two integers *l* and *r* (1<=β€<=*l*<=β€<=*r*<=β€<=*n*) such that . In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.
The expression means applying the operation of a bitwise xor to numbers *x* and *y*. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal β as "xor".
In this problem you are asked to compute the number of sequences made of *n* integers from 0 to 2*m*<=-<=1 that are not a wool sequence. You should print this number modulo 1000000009 (109<=+<=9).
Input Specification:
The only line of input contains two space-separated integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=105).
Output Specification:
Print the required number of sequences modulo 1000000009 (109<=+<=9) on the only line of output.
Demo Input:
['3 2\n']
Demo Output:
['6\n']
Note:
Sequences of length 3 made of integers 0, 1, 2 and 3 that are not a wool sequence are (1, 3, 1), (1, 2, 1), (2, 1, 2), (2, 3, 2), (3, 1, 3) and (3, 2, 3). | 1,413 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You play the game with your friend. The description of this game is listed below.
Your friend creates *n* distinct strings of the same length *m* and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the *n* strings equals . You want to guess which string was chosen by your friend.
In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position *pos* in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions.
You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=50)Β β the number of strings your friend came up with.
The next *n* lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
Output Specification:
Print the single number β the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=9.
Demo Input:
['2\naab\naac\n', '3\naaA\naBa\nCaa\n', '3\naca\nvac\nwqq\n']
Demo Output:
['2.000000000000000\n', '1.666666666666667\n', '1.000000000000000\n']
Note:
In the first sample the strings only differ in the character in the third position. So only the following situations are possible:
- you guess the string in one question. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/>; - you guess the string in two questions. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/caddcdaf0d707d9e4ffa41e63e462a3c90474546.png" style="max-width: 100.0%;max-height: 100.0%;"/> Β· <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6bb1686dc4a3e6a10e00b92d434455668cb330a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/> (as in this case the first question should ask about the position that is other than the third one); - you guess the string in three questions. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/caddcdaf0d707d9e4ffa41e63e462a3c90474546.png" style="max-width: 100.0%;max-height: 100.0%;"/> Β· <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6bb1686dc4a3e6a10e00b92d434455668cb330a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> Β· <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a53d50910d43b79b6602f97f9fde950c9d1bdf77.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/>;
Thus, the expected value is equal to <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5f789afab0601bacf9123c73584184ef358740fb.png" style="max-width: 100.0%;max-height: 100.0%;"/>
In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/208df5d4b6316ba263eede5d4cf4b844075718f1.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the third sample whatever position we ask about in the first question, we immediately identify the string. | 1,414 |
Title: Sereja and the Arrangement of Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's call an array consisting of *n* integer numbers *a*1, *a*2, ..., *a**n*, beautiful if it has the following property:
- consider all pairs of numbers *x*,<=*y* (*x*<=β <=*y*), such that number *x* occurs in the array *a* and number *y* occurs in the array *a*; - for each pair *x*,<=*y* must exist some position *j* (1<=β€<=*j*<=<<=*n*), such that at least one of the two conditions are met, either *a**j*<==<=*x*,<=*a**j*<=+<=1<==<=*y*, or *a**j*<==<=*y*,<=*a**j*<=+<=1<==<=*x*.
Sereja wants to build a beautiful array *a*, consisting of *n* integers. But not everything is so easy, Sereja's friend Dima has *m* coupons, each contains two integers *q**i*,<=*w**i*. Coupon *i* costs *w**i* and allows you to use as many numbers *q**i* as you want when constructing the array *a*. Values *q**i* are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array *a* of *n* elements. After that he takes *w**i* rubles from Sereja for each *q**i*, which occurs in the array *a*. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.
Help Sereja, find the maximum amount of money he can pay to Dima.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*<=β€<=2Β·106,<=1<=β€<=*m*<=β€<=105). Next *m* lines contain pairs of integers. The *i*-th line contains numbers *q**i*,<=*w**i* (1<=β€<=*q**i*,<=*w**i*<=β€<=105).
It is guaranteed that all *q**i* are distinct.
Output Specification:
In a single line print maximum amount of money (in rubles) Sereja can pay.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Demo Input:
['5 2\n1 2\n2 3\n', '100 3\n1 2\n2 1\n3 1\n', '1 2\n1 1\n2 100\n']
Demo Output:
['5\n', '4\n', '100\n']
Note:
In the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1,β2,β1,β2,β2]. There are another optimal arrays for this test.
In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2]. | 1,415 |
Title: TV Game
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There is a new TV game on BerTV. In this game two players get a number *A* consisting of 2*n* digits. Before each turn players determine who will make the next move. Each player should make exactly *n* moves. On it's turn *i*-th player takes the leftmost digit of *A* and appends it to his or her number *S**i*. After that this leftmost digit is erased from *A*. Initially the numbers of both players (*S*1 and *S*2) are Β«emptyΒ». Leading zeroes in numbers *A*,<=*S*1,<=*S*2 are allowed. In the end of the game the first player gets *S*1 dollars, and the second gets *S*2 dollars.
One day Homer and Marge came to play the game. They managed to know the number *A* beforehand. They want to find such sequence of their moves that both of them makes exactly *n* moves and which maximizes their total prize. Help them.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=18). The second line contains integer *A* consisting of exactly 2*n* digits. This number can have leading zeroes.
Output Specification:
Output the line of 2*n* characters Β«HΒ» and Β«MΒ» β the sequence of moves of Homer and Marge, which gives them maximum possible total prize. Each player must make exactly *n* moves. If there are several solutions, output any of them.
Demo Input:
['2\n1234\n', '2\n9911\n']
Demo Output:
['HHMM', 'HMHM']
Note:
none | 1,416 |
Title: Palindrome Degree
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
String *s* of length *n* is called *k*-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (*k*<=-<=1)-palindromes. By definition, any string (even empty) is 0-palindrome.
Let's call the palindrome degree of string *s* such a maximum number *k*, for which *s* is *k*-palindrome. For example, "abaaba" has degree equals to 3.
You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
Input Specification:
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5Β·106. The string is case-sensitive.
Output Specification:
Output the only number β the sum of the polindrome degrees of all the string's prefixes.
Demo Input:
['a2A\n', 'abacaba\n']
Demo Output:
['1', '6']
Note:
none | 1,417 |
Title: Constructing Tests
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's denote a *m*-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size *m*<=Γ<=*m* of this matrix contains at least one zero.
Consider the following problem:
You are given two integers *n* and *m*. You have to construct an *m*-free square matrix of size *n*<=Γ<=*n* such that the number of 1's in this matrix is maximum possible. Print the maximum possible number of 1's in such matrix.
You don't have to solve this problem. Instead, you have to construct a few tests for it.
You will be given *t* numbers *x*1, *x*2, ..., *x**t*. For every , find two integers *n**i* and *m**i* (*n**i*<=β₯<=*m**i*) such that the answer for the aforementioned problem is exactly *x**i* if we set *n*<==<=*n**i* and *m*<==<=*m**i*.
Input Specification:
The first line contains one integer *t* (1<=β€<=*t*<=β€<=100) β the number of tests you have to construct.
Then *t* lines follow, *i*-th line containing one integer *x**i* (0<=β€<=*x**i*<=β€<=109).
Note that in hacks you have to set *t*<==<=1.
Output Specification:
For each test you have to construct, output two positive numbers *n**i* and *m**i* (1<=β€<=*m**i*<=β€<=*n**i*<=β€<=109) such that the maximum number of 1's in a *m**i*-free *n**i*<=Γ<=*n**i* matrix is exactly *x**i*. If there are multiple solutions, you may output any of them; and if this is impossible to construct a test, output a single integer <=-<=1.
Demo Input:
['3\n21\n0\n1\n']
Demo Output:
['5 2\n1 1\n-1\n']
Note:
none | 1,418 |
Title: Suitable Replacement
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two strings *s* and *t* consisting of small Latin letters, string *s* can also contain '?' characters.
Suitability of string *s* is calculated by following metric:
Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings *s*, you choose the one with the largest number of non-intersecting occurrences of string *t*. Suitability is this number of occurrences.
You should replace all '?' characters with small Latin letters in such a way that the suitability of string *s* is maximal.
Input Specification:
The first line contains string *s* (1<=β€<=|*s*|<=β€<=106).
The second line contains string *t* (1<=β€<=|*t*|<=β€<=106).
Output Specification:
Print string *s* with '?' replaced with small Latin letters in such a way that suitability of that string is maximal.
If there are multiple strings with maximal suitability then print any of them.
Demo Input:
['?aa?\nab\n', '??b?\nza\n', 'abcd\nabacaba\n']
Demo Output:
['baab\n', 'azbz\n', 'abcd\n']
Note:
In the first example string "baab" can be transformed to "abab" with swaps, this one has suitability of 2. That means that string "baab" also has suitability of 2.
In the second example maximal suitability you can achieve is 1 and there are several dozens of such strings, "azbz" is just one of them.
In the third example there are no '?' characters and the suitability of the string is 0. | 1,419 |
Title: Vanya and Fence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input Specification:
The first line of the input contains two integers *n* and *h* (1<=β€<=*n*<=β€<=1000, 1<=β€<=*h*<=β€<=1000)Β β the number of friends and the height of the fence, respectively.
The second line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=2*h*), the *i*-th of them is equal to the height of the *i*-th person.
Output Specification:
Print a single integerΒ β the minimum possible valid width of the road.
Demo Input:
['3 7\n4 5 14\n', '6 1\n1 1 1 1 1 1\n', '6 5\n7 6 8 9 10 5\n']
Demo Output:
['4\n', '6\n', '11\n']
Note:
In the first sample, only person number 3 must bend down, so the required width is equal to 1β+β1β+β2β=β4.
In the second sample, all friends are short enough and no one has to bend, so the width 1β+β1β+β1β+β1β+β1β+β1β=β6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2β+β2β+β2β+β2β+β2β+β1β=β11. | 1,420 |
Title: Case of Computer Network
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network.
In this network are *n* vertices, some pairs of vertices are connected by *m* undirected channels. It is planned to transfer *q* important messages via this network, the *i*-th of which must be sent from vertex *s**i* to vertex *d**i* via one or more channels, perhaps through some intermediate vertices.
To protect against attacks a special algorithm was developed. Unfortunately it can be applied only to the network containing directed channels. Therefore, as new channels can't be created, it was decided for each of the existing undirected channels to enable them to transmit data only in one of the two directions.
Your task is to determine whether it is possible so to choose the direction for each channel so that each of the *q* messages could be successfully transmitted.
Input Specification:
The first line contains three integers *n*, *m* and *q* (1<=β€<=*n*,<=*m*,<=*q*<=β€<=2Β·105) β the number of nodes, channels and important messages.
Next *m* lines contain two integers each, *v**i* and *u**i* (1<=β€<=*v**i*,<=*u**i*<=β€<=*n*, *v**i*<=β <=*u**i*), that means that between nodes *v**i* and *u**i* is a channel. Between a pair of nodes can exist more than one channel.
Next *q* lines contain two integers *s**i* and *d**i* (1<=β€<=*s**i*,<=*d**i*<=β€<=*n*, *s**i*<=β <=*d**i*) β the numbers of the nodes of the source and destination of the corresponding message.
It is not guaranteed that in it initially possible to transmit all the messages.
Output Specification:
If a solution exists, print on a single line "Yes" (without the quotes). Otherwise, print "No" (without the quotes).
Demo Input:
['4 4 2\n1 2\n1 3\n2 3\n3 4\n1 3\n4 2\n', '3 2 2\n1 2\n3 2\n1 3\n2 1\n', '3 3 2\n1 2\n1 2\n3 2\n1 3\n2 1\n']
Demo Output:
['Yes\n', 'No\n', 'Yes\n']
Note:
In the first sample test you can assign directions, for example, as follows: 1βββ2, 1βββ3, 3βββ2, 4βββ3. Then the path for for the first message will be 1βββ3, and for the second one β 4βββ3βββ2.
In the third sample test you can assign directions, for example, as follows: 1βββ2, 2βββ1, 2βββ3. Then the path for the first message will be 1βββ2βββ3, and for the second one β 2βββ1. | 1,421 |
Title: Nastya and a Wardrobe
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Nastya received a gift on New YearΒ β a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).
Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the 50% probability. It happens every month except the last one in the year.
Nastya owns *x* dresses now, so she became interested in the [expected number](https://en.wikipedia.org/wiki/Expected_value) of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for *k*<=+<=1 months.
Nastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo 109<=+<=7, because it is easy to see that it is always integer.
Input Specification:
The only line contains two integers *x* and *k* (0<=β€<=*x*,<=*k*<=β€<=1018), where *x* is the initial number of dresses and *k*<=+<=1 is the number of months in a year in Byteland.
Output Specification:
In the only line print a single integerΒ β the expected number of dresses Nastya will own one year later modulo 109<=+<=7.
Demo Input:
['2 0\n', '2 1\n', '3 2\n']
Demo Output:
['4\n', '7\n', '21\n']
Note:
In the first example a year consists on only one month, so the wardrobe does not eat dresses at all.
In the second example after the first month there are 3 dresses with 50% probability and 4 dresses with 50% probability. Thus, in the end of the year there are 6 dresses with 50% probability and 8 dresses with 50% probability. This way the answer for this test is (6β+β8)β/β2β=β7. | 1,422 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.
The forest
The Biridian Forest is a two-dimensional grid consisting of *r* rows and *c* columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.
The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):
Moves
Breeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:
- Do nothing. - Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees. - If you are located on the exit cell, you may leave the forest. Only you can perform this move β all other mikemon breeders will never leave the forest by using this type of movement.
After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).
Mikemon battle
If you and *t* (*t*<=><=0) mikemon breeders are located on the same cell, exactly *t* mikemon battles will ensue that time (since you will be battling each of those *t* breeders once). After the battle, all of those *t* breeders will leave the forest to heal their respective mikemons.
Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders β there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).
Your goal
You would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.
Goal of other breeders
Because you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.
Your task
Print the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.
Input Specification:
The first line consists of two integers: *r* and *c* (1<=β€<=*r*,<=*c*<=β€<=1000), denoting the number of rows and the number of columns in Biridian Forest. The next *r* rows will each depict a row of the map, where each character represents the content of a single cell:
- 'T': A cell occupied by a tree. - 'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map. - 'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map. - A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder).
It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.
Output Specification:
A single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.
Demo Input:
['5 7\n000E0T3\nT0TT0T0\n010T0T0\n2T0T0T0\n0T0S000\n', '1 4\nSE23\n']
Demo Output:
['3\n', '2\n']
Note:
The following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog:
The three breeders on the left side of the map will be able to battle you β the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.
For the second example, you should post this sequence in your Blog:
Here's what happens. First, you move one cell to the right.
Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing.
You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest.
Finally, you make another move by leaving the forest. | 1,423 |
Title: Writing a Song
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names.
The friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name will be repeated many times. But try as he might, he can't write a decent song!
The problem is that the Hedgehog has already decided how long the resulting sentence should be (i.e. how many letters it should contain) and in which positions in the sentence the friend's name should occur, and it must not occur in any other position in the sentence. Besides, the Hedgehog decided to limit himself to using only the first *K* letters of an English alphabet in this sentence (so it will be not even a sentence, but one long word).
The resulting problem is indeed quite complicated, that's why the Hedgehog asks you to help him and write a program that will make the desired word by the given name *P*, the length *N* of the required word, the given positions of the occurrences of the name *P* in the desired word and the alphabet's size *K*. Note that the occurrences of the name can overlap with each other.
Input Specification:
The first line contains numbers *N* and *K* which are the length of the required string and the alphabet size accordingly. The limitations are: 1<=β€<=*N*<=β€<=100, 2<=β€<=*K*<=β€<=26.
The second line contains the name *P* which is a non-empty string whose length does not exceed *N* characters. The string consists only of the first *K* lowercase symbols of an English alphabet.
The third line contains the string of length *N*<=-<=*length*(*P*)<=+<=1, consisting only of numbers zero and one. A number one in the *i*-th position means that an occurrence of the name *P* should start from *i*-th position of the desired word, while a zero means that there is no occurrence starting here.
Output Specification:
Print the desired word *S*. If there are several answers, print any of them.
If there is no solution, then print "No solution".
Demo Input:
['5 2\naba\n101\n', '5 2\na\n10001\n', '6 2\nabba\n101\n']
Demo Output:
['ababa', 'abbba', 'No solution']
Note:
none | 1,424 |
Title: Modulo Sum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a sequence of numbers *a*1,<=*a*2,<=...,<=*a**n*, and a number *m*.
Check if it is possible to choose a non-empty subsequence *a**i**j* such that the sum of numbers in this subsequence is divisible by *m*.
Input Specification:
The first line contains two numbers, *n* and *m* (1<=β€<=*n*<=β€<=106, 2<=β€<=*m*<=β€<=103) β the size of the original sequence and the number such that sum should be divisible by it.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=109).
Output Specification:
In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.
Demo Input:
['3 5\n1 2 3\n', '1 6\n5\n', '4 6\n3 1 1 3\n', '6 6\n5 5 5 5 5 5\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n', 'YES\n']
Note:
In the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.
In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.
In the third sample test you need to choose two numbers 3 on the ends.
In the fourth sample test you can take the whole subsequence. | 1,425 |
Title: Choosing Teams
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least *k* times?
Input Specification:
The first line contains two integers, *n* and *k* (1<=β€<=*n*<=β€<=2000;Β 1<=β€<=*k*<=β€<=5). The next line contains *n* integers: *y*1,<=*y*2,<=...,<=*y**n* (0<=β€<=*y**i*<=β€<=5), where *y**i* shows the number of times the *i*-th person participated in the ACM ICPC world championship.
Output Specification:
Print a single number β the answer to the problem.
Demo Input:
['5 2\n0 4 5 1 0\n', '6 4\n0 1 2 3 4 5\n', '6 5\n0 0 0 0 0 0\n']
Demo Output:
['1\n', '0\n', '2\n']
Note:
In the first sample only one team could be made: the first, the fourth and the fifth participants.
In the second sample no teams could be created.
In the third sample two teams could be created. Any partition into two teams fits. | 1,426 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Zxr960115 is owner of a large farm. He feeds *m* cute cats and employs *p* feeders. There's a straight road across the farm and *n* hills along the road, numbered from 1 to *n* from left to right. The distance between hill *i* and (*i*<=-<=1) is *d**i* meters. The feeders live in hill 1.
One day, the cats went out to play. Cat *i* went on a trip to hill *h**i*, finished its trip at time *t**i*, and then waited at hill *h**i* for a feeder. The feeders must take all the cats. Each feeder goes straightly from hill 1 to *n* without waiting at a hill and takes all the waiting cats at each hill away. Feeders walk at a speed of 1 meter per unit time and are strong enough to take as many cats as they want.
For example, suppose we have two hills (*d*2<==<=1) and one cat that finished its trip at time 3 at hill 2 (*h*1<==<=2). Then if the feeder leaves hill 1 at time 2 or at time 3, he can take this cat, but if he leaves hill 1 at time 1 he can't take it. If the feeder leaves hill 1 at time 2, the cat waits him for 0 time units, if the feeder leaves hill 1 at time 3, the cat waits him for 1 time units.
Your task is to schedule the time leaving from hill 1 for each feeder so that the sum of the waiting time of all cats is minimized.
Input Specification:
The first line of the input contains three integers *n*,<=*m*,<=*p* (2<=β€<=*n*<=β€<=105,<=1<=β€<=*m*<=β€<=105,<=1<=β€<=*p*<=β€<=100).
The second line contains *n*<=-<=1 positive integers *d*2,<=*d*3,<=...,<=*d**n* (1<=β€<=*d**i*<=<<=104).
Each of the next *m* lines contains two integers *h**i* and *t**i* (1<=β€<=*h**i*<=β€<=*n*,<=0<=β€<=*t**i*<=β€<=109).
Output Specification:
Output an integer, the minimum sum of waiting time of all cats.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Demo Input:
['4 6 2\n1 3 5\n1 0\n2 1\n4 9\n1 10\n2 10\n3 12\n']
Demo Output:
['3\n']
Note:
none | 1,427 |
Title: Elevator
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You work in a big office. It is a 9Β floor building with an elevator that can accommodate up to 4Β people. It is your responsibility to manage this elevator.
Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.
According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.
The elevator has two commands:
- Go up or down one floor. The movement takes 1 second. - Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator.
Initially the elevator is empty and is located on the floor 1.
You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
Input Specification:
The first line contains an integer *n* (1<=β€<=*n*<=β€<=2000)Β β the number of employees.
The *i*-th of the next *n* lines contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=9, *a**i*<=β <=*b**i*)Β β the floor on which an employee initially is, and the floor he wants to reach.
The employees are given in the order they came to the elevator.
Output Specification:
Print a single integerΒ β the minimal possible time in seconds.
Demo Input:
['2\n3 5\n5 3\n', '2\n5 3\n3 5\n']
Demo Output:
['10', '12']
Note:
<img class="tex-graphics" src="https://espresso.codeforces.com/1b7e25450a0703db67675fea25386865f0290049.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t*β=β2
<img class="tex-graphics" src="https://espresso.codeforces.com/0f585328ada5689c39e5a7263a792979c00fb01a.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t*β=β3
<img class="tex-graphics" src="https://espresso.codeforces.com/61f0c2263487060af2083a06cedf6641d234e31b.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t*β=β5
<img class="tex-graphics" src="https://espresso.codeforces.com/4f5d7a22c1f2af851019589a1232851ced924fbf.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t*β=β6
<img class="tex-graphics" src="https://espresso.codeforces.com/4602434598e4844e9532caef51583bd84886b067.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t*β=β7
<img class="tex-graphics" src="https://espresso.codeforces.com/c1924de28ca19fe1346617380752126a2d4bbb75.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t*β=β9
<img class="tex-graphics" src="https://espresso.codeforces.com/2e58cd09a6a459da60780a790c49da336d0b2783.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t*β=β10 | 1,428 |
Title: Pattern
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.
In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.
Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given *n* patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=105) β the number of patterns. Next *n* lines contain the patterns.
It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.
Output Specification:
In a single line print the answer to the problem β the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.
Demo Input:
['2\n?ab\n??b\n', '2\na\nb\n', '1\n?a?b\n']
Demo Output:
['xab\n', '?\n', 'cacb\n']
Note:
Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on. | 1,429 |
Title: Sale
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price β their owners are ready to pay Bob if he buys their useless apparatus. Bob can Β«buyΒ» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
Input Specification:
The first line contains two space-separated integers *n* and *m* (1<=β€<=*m*<=β€<=*n*<=β€<=100) β amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains *n* space-separated integers *a**i* (<=-<=1000<=β€<=*a**i*<=β€<=1000) β prices of the TV sets.
Output Specification:
Output the only number β the maximum sum of money that Bob can earn, given that he can carry at most *m* TV sets.
Demo Input:
['5 3\n-6 0 35 -2 4\n', '4 2\n7 0 0 -7\n']
Demo Output:
['8\n', '7\n']
Note:
none | 1,430 |
Title: PolandBall and Polygon
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
PolandBall has such a convex polygon with *n* veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments.
He chose a number *k* such that *gcd*(*n*,<=*k*)<==<=1. Vertices of the polygon are numbered from 1 to *n* in a clockwise way. PolandBall repeats the following process *n* times, starting from the vertex 1:
Assume you've ended last operation in vertex *x* (consider *x*<==<=1 if it is the first operation). Draw a new segment from vertex *x* to *k*-th next vertex in clockwise direction. This is a vertex *x*<=+<=*k* or *x*<=+<=*k*<=-<=*n* depending on which of these is a valid index of polygon's vertex.
Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.
Input Specification:
There are only two numbers in the input: *n* and *k* (5<=β€<=*n*<=β€<=106, 2<=β€<=*k*<=β€<=*n*<=-<=2, *gcd*(*n*,<=*k*)<==<=1).
Output Specification:
You should print *n* values separated by spaces. The *i*-th value should represent number of polygon's sections after drawing first *i* lines.
Demo Input:
['5 2\n', '10 3\n']
Demo Output:
['2 3 5 8 11 ', '2 3 4 6 9 12 16 21 26 31 ']
Note:
The greatest common divisor (gcd) of two integers *a* and *b* is the largest positive integer that divides both *a* and *b* without a remainder.
For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines. | 1,431 |
Title: Psychos in a Line
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* psychos standing in a line. Each psycho is assigned a unique integer from 1 to *n*. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input Specification:
The first line of input contains integer *n* denoting the number of psychos, (1<=β€<=*n*<=β€<=105). In the second line there will be a list of *n* space separated distinct integers each in range 1 to *n*, inclusive β ids of the psychos in the line from left to right.
Output Specification:
Print the number of steps, so that the line remains the same afterward.
Demo Input:
['10\n10 9 7 8 6 5 3 4 2 1\n', '6\n1 2 3 4 5 6\n']
Demo Output:
['2\n', '0\n']
Note:
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] βββ [10 8 4] βββ [10]. So, there are two steps. | 1,432 |
Title: Sasha and Sticks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws *n* sticks in a row. After that the players take turns crossing out exactly *k* sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than *k* sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*n*,<=*k*<=β€<=1018, *k*<=β€<=*n*)Β β the number of sticks drawn by Sasha and the number *k*Β β the number of sticks to be crossed out on each turn.
Output Specification:
If Sasha wins, print "YES" (without quotes), otherwise print "NO" (without quotes).
You can print each letter in arbitrary case (upper of lower).
Demo Input:
['1 1\n', '10 4\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first example Sasha crosses out 1 stick, and then there are no sticks. So Lena can't make a move, and Sasha wins.
In the second example Sasha crosses out 4 sticks, then Lena crosses out 4 sticks, and after that there are only 2 sticks left. Sasha can't make a move. The players make equal number of moves, so Sasha doesn't win. | 1,433 |
Title: Put Knight!
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard *n*<=Γ<=*n* in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (*r*,<=*c*) can threat squares (*r*<=-<=1,<=*c*<=+<=2), (*r*<=-<=1,<=*c*<=-<=2), (*r*<=+<=1,<=*c*<=+<=2), (*r*<=+<=1,<=*c*<=-<=2), (*r*<=-<=2,<=*c*<=+<=1), (*r*<=-<=2,<=*c*<=-<=1), (*r*<=+<=2,<=*c*<=+<=1) and (*r*<=+<=2,<=*c*<=-<=1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.
Input Specification:
The first line contains integer *T* (1<=β€<=*T*<=β€<=100) β the number of boards, for which you should determine the winning player. Next *T* lines contain *T* integers *n**i* (1<=β€<=*n**i*<=β€<=10000) β the sizes of the chessboards.
Output Specification:
For each *n**i*<=Γ<=*n**i* board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1".
Demo Input:
['2\n2\n1\n']
Demo Output:
['1\n0\n']
Note:
none | 1,434 |
Title: Interestring graph and Apples
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life Β«interesting graph and applesΒ». An undirected graph is called interesting, if each of its vertices belongs to one cycle only β a funny ring β and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.
She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*), where *x**i*<=β€<=*y**i*, is lexicographically smaller than the set (*u*1,<=*v*1),<=(*u*2,<=*v*2),<=...,<=(*u**n*,<=*v**n*), where *u**i*<=β€<=*v**i*, provided that the sequence of integers *x*1,<=*y*1,<=*x*2,<=*y*2,<=...,<=*x**n*,<=*y**n* is lexicographically smaller than the sequence *u*1,<=*v*1,<=*u*2,<=*v*2,<=...,<=*u**n*,<=*v**n*. If you do not cope, Hexadecimal will eat you. ...eat you alive.
Input Specification:
The first line of the input data contains a pair of integers *n* and *m* (1<=β€<=*n*<=β€<=50, 0<=β€<=*m*<=β€<=2500) β the amount of vertices and edges respectively. The following lines contain pairs of numbers *x**i* and *y**i* (1<=β€<=*x**i*, *y**i*<=β€<=*n*) β the vertices that are already connected by edges. The initial graph may contain multiple edges and loops.
Output Specification:
In the first line output Β«YESΒ» or Β«NOΒ»: if it is possible or not to construct an interesting graph. If the answer is Β«YESΒ», in the second line output *k* β the amount of edges that should be added to the initial graph. Finally, output *k* lines: pairs of vertices *x**j* and *y**j*, between which edges should be drawn. The result may contain multiple edges and loops. *k* can be equal to zero.
Demo Input:
['3 2\n1 2\n2 3\n']
Demo Output:
['YES\n1\n1 3\n']
Note:
none | 1,435 |
Title: Flow Control
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have to handle a very complex water distribution system. The system consists of $n$ junctions and $m$ pipes, $i$-th pipe connects junctions $x_i$ and $y_i$.
The only thing you can do is adjusting the pipes. You have to choose $m$ integer numbers $f_1$, $f_2$, ..., $f_m$ and use them as pipe settings. $i$-th pipe will distribute $f_i$ units of water per second from junction $x_i$ to junction $y_i$ (if $f_i$ is negative, then the pipe will distribute $|f_i|$ units of water per second from junction $y_i$ to junction $x_i$). It is allowed to set $f_i$ to any integer from $-2 \cdot 10^9$ to $2 \cdot 10^9$.
In order for the system to work properly, there are some constraints: for every $i \in [1, n]$, $i$-th junction has a number $s_i$ associated with it meaning that the difference between incoming and outcoming flow for $i$-th junction must be exactly $s_i$ (if $s_i$ is not negative, then $i$-th junction must receive $s_i$ units of water per second; if it is negative, then $i$-th junction must transfer $|s_i|$ units of water per second to other junctions).
Can you choose the integers $f_1$, $f_2$, ..., $f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied?
Input Specification:
The first line contains an integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of junctions.
The second line contains $n$ integers $s_1, s_2, \dots, s_n$ ($-10^4 \le s_i \le 10^4$) β constraints for the junctions.
The third line contains an integer $m$ ($0 \le m \le 2 \cdot 10^5$) β the number of pipes.
$i$-th of the next $m$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$) β the description of $i$-th pipe. It is guaranteed that each unordered pair $(x, y)$ will appear no more than once in the input (it means that there won't be any pairs $(x, y)$ or $(y, x)$ after the first occurrence of $(x, y)$). It is guaranteed that for each pair of junctions there exists a path along the pipes connecting them.
Output Specification:
If you can choose such integer numbers $f_1, f_2, \dots, f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied, then output "Possible" in the first line. Then output $m$ lines, $i$-th line should contain $f_i$ β the chosen setting numbers for the pipes. Pipes are numbered in order they appear in the input.
Otherwise output "Impossible" in the only line.
Demo Input:
['4\n3 -10 6 1\n5\n1 2\n3 2\n2 4\n3 4\n3 1\n', '4\n3 -10 6 4\n5\n1 2\n3 2\n2 4\n3 4\n3 1\n']
Demo Output:
['Possible\n4\n-6\n8\n-7\n7\n', 'Impossible\n']
Note:
none | 1,436 |
Title: Need For Brake
Time Limit: 4 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game!
*n* racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to *n*-th (no two racers share the same place) and first *m* places are awarded. Racer gains *b**i* points for *i*-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer *i* is *a**i* points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.
Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship.
Input Specification:
The first line contains number *n* (1<=β€<=*n*<=β€<=105) β number of racers. Each of the next *n* lines contains *s**i* and *a**i* β nick of the racer (nonempty string, which consist of no more than 20 lowercase Latin letters) and the racer's points (0<=β€<=*a**i*<=β€<=106). Racers are given in the arbitrary order.
The next line contains the number *m* (0<=β€<=*m*<=β€<=*n*). Then *m* nonnegative integer numbers *b**i* follow. *i*-th number is equal to amount of points for the *i*-th awarded place (0<=β€<=*b**i*<=β€<=106).
The last line contains Vasya's racer nick.
Output Specification:
Output two numbers β the highest and the lowest place Vasya can take up as a result of the championship.
Demo Input:
['3\nteama 10\nteamb 20\nteamc 40\n2\n10 20\nteama\n', '2\nteama 10\nteamb 10\n2\n10 10\nteamb\n']
Demo Output:
['2 3', '2 2']
Note:
none | 1,437 |
Title: Secrets
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gerald has been selling state secrets at leisure. All the secrets cost the same: *n* marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.
One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?
The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of *n* marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least *n* marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.
Input Specification:
The single line contains a single integer *n* (1<=β€<=*n*<=β€<=1017).
Please, do not use the %lld specifier to read or write 64 bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output Specification:
In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with.
Demo Input:
['1\n', '4\n']
Demo Output:
['1\n', '2\n']
Note:
In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.
In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives. | 1,438 |
Title: Binary Tree on Plane
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A root tree is a directed acyclic graph that contains one node (root), from which there is exactly one path to any other node.
A root tree is binary if each node has at most two outgoing arcs.
When a binary tree is painted on the plane, all arcs should be directed from top to bottom. That is, each arc going from *u* to *v* must meet the condition *y**u*<=><=*y**v*.
You've been given the coordinates of all tree nodes. Your task is to connect these nodes by arcs so as to get the binary root tree and make the total length of the arcs minimum. All arcs of the built tree must be directed from top to bottom.
Input Specification:
The first line contains a single integer *n* (2<=β€<=*n*<=β€<=400) β the number of nodes in the tree. Then follow *n* lines, two integers per line: *x**i*,<=*y**i* (|*x**i*|,<=|*y**i*|<=β€<=103) β coordinates of the nodes. It is guaranteed that all points are distinct.
Output Specification:
If it is impossible to build a binary root tree on the given points, print "-1". Otherwise, print a single real number β the total length of the arcs in the minimum binary tree. The answer will be considered correct if the absolute or relative error doesn't exceed 10<=-<=6.
Demo Input:
['3\n0 0\n1 0\n2 1\n', '4\n0 0\n1 0\n2 1\n2 0\n']
Demo Output:
['3.650281539872885\n', '-1\n']
Note:
none | 1,439 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Little Elephant has two permutations *a* and *b* of length *n*, consisting of numbers from 1 to *n*, inclusive. Let's denote the *i*-th (1<=β€<=*i*<=β€<=*n*) element of the permutation *a* as *a**i*, the *j*-th (1<=β€<=*j*<=β€<=*n*) element of the permutation *b* β as *b**j*.
The distance between permutations *a* and *b* is the minimum absolute value of the difference between the positions of the occurrences of some number in *a* and in *b*. More formally, it's such minimum |*i*<=-<=*j*|, that *a**i*<==<=*b**j*.
A cyclic shift number *i* (1<=β€<=*i*<=β€<=*n*) of permutation *b* consisting from *n* elements is a permutation *b**i**b**i*<=+<=1... *b**n**b*1*b*2... *b**i*<=-<=1. Overall a permutation has *n* cyclic shifts.
The Little Elephant wonders, for all cyclic shifts of permutation *b*, what is the distance between the cyclic shift and permutation *a*?
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=105) β the size of the permutations. The second line contains permutation *a* as *n* distinct numbers from 1 to *n*, inclusive. The numbers are separated with single spaces. The third line contains permutation *b* in the same format.
Output Specification:
In *n* lines print *n* integers β the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation *b*, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.
Demo Input:
['2\n1 2\n2 1\n', '4\n2 1 3 4\n3 4 2 1\n']
Demo Output:
['1\n0\n', '2\n1\n0\n1\n']
Note:
none | 1,440 |
Title: Vladik and chat
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently Vladik discovered a new entertainmentΒ β coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.
At first, he need to download *t* chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.
Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.
He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
Input Specification:
The first line contains single integer *t* (1<=β€<=*t*<=β€<=10) β the number of chats. The *t* chats follow. Each chat is given in the following format.
The first line of each chat description contains single integer *n* (1<=β€<=*n*<=β€<=100)Β β the number of users in the chat.
The next line contains *n* space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.
The next line contains single integer *m* (1<=β€<=*m*<=β€<=100)Β β the number of messages in the chat. The next *m* line contain the messages in the following formats, one per line:
- <username>:<text>Β β the format of a message with known sender. The username should appear in the list of usernames of the chat. - <?>:<text>Β β the format of a message with unknown sender.
The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters.
We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha".
It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
Output Specification:
Print the information about the *t* chats in the following format:
If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print *m* messages in the following format:
<username>:<text>
If there are multiple answers, print any of them.
Demo Input:
['1\n2\nVladik netman\n2\n?: Hello, Vladik!\n?: Hi\n', '1\n2\nnetman vladik\n3\nnetman:how are you?\n?:wrong message\nvladik:im fine\n', '2\n3\nnetman vladik Fedosik\n2\n?: users are netman, vladik, Fedosik\nvladik: something wrong with this chat\n4\nnetman tigerrrrr banany2001 klinchuh\n4\n?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\nklinchuh: yes, coach!\n?: yes, netman\nbanany2001: yes of course.\n']
Demo Output:
['netman: Hello, Vladik!\nVladik: Hi\n', 'Impossible\n', 'Impossible\nnetman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\nklinchuh: yes, coach!\ntigerrrrr: yes, netman\nbanany2001: yes of course.\n']
Note:
none | 1,441 |
Title: Music in Car
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sasha reaches the work by car. It takes exactly *k* minutes. On his way he listens to music. All songs in his playlist go one by one, after listening to the *i*-th song Sasha gets a pleasure which equals *a**i*. The *i*-th song lasts for *t**i* minutes.
Before the beginning of his way Sasha turns on some song *x* and then he listens to the songs one by one: at first, the song *x*, then the song (*x*<=+<=1), then the song number (*x*<=+<=2), and so on. He listens to songs until he reaches the work or until he listens to the last song in his playlist.
Sasha can listen to each song to the end or partly.
In the second case he listens to the song for integer number of minutes, at least half of the song's length. Formally, if the length of the song equals *d* minutes, Sasha listens to it for no less than minutes, then he immediately switches it to the next song (if there is such). For example, if the length of the song which Sasha wants to partly listen to, equals 5 minutes, then he should listen to it for at least 3 minutes, if the length of the song equals 8 minutes, then he should listen to it for at least 4 minutes.
It takes no time to switch a song.
Sasha wants to listen partly no more than *w* songs. If the last listened song plays for less than half of its length, then Sasha doesn't get pleasure from it and that song is not included to the list of partly listened songs. It is not allowed to skip songs. A pleasure from a song does not depend on the listening mode, for the *i*-th song this value equals *a**i*.
Help Sasha to choose such *x* and no more than *w* songs for partial listening to get the maximum pleasure. Write a program to find the maximum pleasure Sasha can get from the listening to the songs on his way to the work.
Input Specification:
The first line contains three integers *n*, *w* and *k* (1<=β€<=*w*<=β€<=*n*<=β€<=2Β·105, 1<=β€<=*k*<=β€<=2Β·109)Β β the number of songs in the playlist, the number of songs Sasha can listen to partly and time in minutes which Sasha needs to reach work.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=104), where *a**i* equals the pleasure Sasha gets after listening to the *i*-th song.
The third line contains *n* positive integers *t*1,<=*t*2,<=...,<=*t**n* (2<=β€<=*t**i*<=β€<=104), where *t**i* equals the length of the *i*-th song in minutes.
Output Specification:
Print the maximum pleasure Sasha can get after listening to the songs on the way to work.
Demo Input:
['7 2 11\n3 4 3 5 1 4 6\n7 7 3 6 5 3 9\n', '8 4 20\n5 6 4 3 7 5 4 1\n10 12 5 12 14 8 5 8\n', '1 1 5\n6\n9\n', '1 1 3\n4\n7\n']
Demo Output:
['12\n', '19\n', '6\n', '0\n']
Note:
In the first example Sasha needs to start listening from the song number 2. He should listen to it partly (for 4 minutes), then listen to the song number 3 to the end (for 3 minutes) and then partly listen to the song number 4 (for 3 minutes). After listening to these songs Sasha will get pleasure which equals 4β+β3β+β5β=β12. Sasha will not have time to listen to the song number 5 because he will spend 4β+β3β+β3β=β10 minutes listening to songs number 2, 3 and 4 and only 1 minute is left after that. | 1,442 |
Title: Caisa and Pylons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is to reach *n*-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as *k*) to the next one (its number will be *k*<=+<=1). When the player have made such a move, its energy increases by *h**k*<=-<=*h**k*<=+<=1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.
Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=105). The next line contains *n* integers *h*1, *h*2,<=..., *h**n* (1<=<=β€<=<=*h**i*<=<=β€<=<=105) representing the heights of the pylons.
Output Specification:
Print a single number representing the minimum number of dollars paid by Caisa.
Demo Input:
['5\n3 4 3 2 4\n', '3\n4 4 4\n']
Demo Output:
['4\n', '4\n']
Note:
In the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon. | 1,443 |
Title: Playing with Paper
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular *a* mm <=Γ<= *b* mm sheet of paper (*a*<=><=*b*). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.
After making a paper ship from the square piece, Vasya looked on the remaining (*a*<=-<=*b*) mm <=Γ<= *b* mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.
Can you determine how many ships Vasya will make during the lesson?
Input Specification:
The first line of the input contains two integers *a*, *b* (1<=β€<=*b*<=<<=*a*<=β€<=1012) β the sizes of the original sheet of paper.
Output Specification:
Print a single integer β the number of ships that Vasya will make.
Demo Input:
['2 1\n', '10 7\n', '1000000000000 1\n']
Demo Output:
['2\n', '6\n', '1000000000000\n']
Note:
Pictures to the first and second sample test. | 1,444 |
Title: Professor GukiZ's Robot
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Professor GukiZ makes a new robot. The robot are in the point with coordinates (*x*1,<=*y*1) and should go to the point (*x*2,<=*y*2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position.
Input Specification:
The first line contains two integers *x*1,<=*y*1 (<=-<=109<=β€<=*x*1,<=*y*1<=β€<=109) β the start position of the robot.
The second line contains two integers *x*2,<=*y*2 (<=-<=109<=β€<=*x*2,<=*y*2<=β€<=109) β the finish position of the robot.
Output Specification:
Print the only integer *d* β the minimal number of steps to get the finish position.
Demo Input:
['0 0\n4 5\n', '3 4\n6 1\n']
Demo Output:
['5\n', '3\n']
Note:
In the first example robot should increase both of its coordinates by one four times, so it will be in position (4,β4). After that robot should simply increase its *y* coordinate and get the finish position.
In the second example robot should simultaneously increase *x* coordinate and decrease *y* coordinate by one three times. | 1,445 |
Title: Little Robber Girl's Zoo
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers *l* and *r* such that *r*<=-<=*l*<=+<=1 is even. After that animals that occupy positions between *l* and *r* inclusively are rearranged as follows: the animal at position *l* swaps places with the animal at position *l*<=+<=1, the animal *l*<=+<=2 swaps with the animal *l*<=+<=3, ..., finally, the animal at position *r*<=-<=1 swaps with the animal *r*.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20<=000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=100)Β β number of animals in the robber girl's zoo.
The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109), where *a**i* is the height of the animal occupying the *i*-th place.
Output Specification:
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, *i*-th of the lines should contain two space-separated integers *l**i* and *r**i* (1<=β€<=*l**i*<=<<=*r**i*<=β€<=*n*)Β β descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20<=000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Demo Input:
['4\n2 1 4 3\n', '7\n36 28 57 39 66 69 68\n', '5\n1 2 1 2 1\n']
Demo Output:
['1 4\n', '1 4\n6 7\n', '2 5\n3 4\n1 4\n1 4\n']
Note:
Note that you don't have to minimize the number of operations. Any solution that performs at most 20β000 operations is allowed. | 1,446 |
Title: IQ Test
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.
Arithmetic progression is a sequence *a*1, *a*1<=+<=*d*, *a*1<=+<=2*d*, ..., *a*1<=+<=(*n*<=-<=1)*d*, where *a*1 and *d* are any numbers.
Geometric progression is a sequence *b*1, *b*2<==<=*b*1*q*, ..., *b**n*<==<=*b**n*<=-<=1*q*, where *b*1<=β <=0, *q*<=β <=0, *q*<=β <=1.
Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.
Input Specification:
The first line contains exactly four integer numbers between 1 and 1000, inclusively.
Output Specification:
Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element.
Print 42 if the given sequence is not an arithmetic or geometric progression.
Demo Input:
['836 624 412 200\n', '1 334 667 1000\n']
Demo Output:
['-12\n', '1333\n']
Note:
This problem contains very weak pretests! | 1,447 |
Title: Good Subsegments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A permutation $p$ of length $n$ is a sequence $p_1, p_2, \ldots, p_n$ consisting of $n$ distinct integers, each of which from $1$ to $n$ ($1 \leq p_i \leq n$) .
Let's call the subsegment $[l,r]$ of the permutation good if all numbers from the minimum on it to the maximum on this subsegment occur among the numbers $p_l, p_{l+1}, \dots, p_r$.
For example, good segments of permutation $[1, 3, 2, 5, 4]$ are:
- $[1, 1]$, - $[1, 3]$, - $[1, 5]$, - $[2, 2]$, - $[2, 3]$, - $[2, 5]$, - $[3, 3]$, - $[4, 4]$, - $[4, 5]$, - $[5, 5]$.
You are given a permutation $p_1, p_2, \ldots, p_n$.
You need to answer $q$ queries of the form: find the number of good subsegments of the given segment of permutation.
In other words, to answer one query, you need to calculate the number of good subsegments $[x \dots y]$ for some given segment $[l \dots r]$, such that $l \leq x \leq y \leq r$.
Input Specification:
The first line contains a single integer $n$ ($1 \leq n \leq 120000$)Β β the number of elements in the permutation.
The second line contains $n$ distinct integers $p_1, p_2, \ldots, p_n$ separated by spaces ($1 \leq p_i \leq n$).
The third line contains an integer $q$ ($1 \leq q \leq 120000$)Β β number of queries.
The following $q$ lines describe queries, each line contains a pair of integers $l$, $r$ separated by space ($1 \leq l \leq r \leq n$).
Output Specification:
Print a $q$ lines, $i$-th of them should contain a number of good subsegments of a segment, given in the $i$-th query.
Demo Input:
['5\n1 3 2 5 4\n15\n1 1\n1 2\n1 3\n1 4\n1 5\n2 2\n2 3\n2 4\n2 5\n3 3\n3 4\n3 5\n4 4\n4 5\n5 5\n']
Demo Output:
['1\n2\n5\n6\n10\n1\n3\n4\n7\n1\n2\n4\n1\n3\n1\n']
Note:
none | 1,448 |
Title: Civilization
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Andrew plays a game called "Civilization". Dima helps him.
The game has *n* cities and *m* bidirectional roads. The cities are numbered from 1 to *n*. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities *v*1,<=*v*2,<=...,<=*v**k*, that there is a road between any contiguous cities *v**i* and *v**i*<=+<=1 (1<=β€<=*i*<=<<=*k*). The length of the described path equals to (*k*<=-<=1). We assume that two cities lie in the same region if and only if, there is a path connecting these two cities.
During the game events of two types take place:
1. Andrew asks Dima about the length of the longest path in the region where city *x* lies. 1. Andrew asks Dima to merge the region where city *x* lies with the region where city *y* lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them.
Dima finds it hard to execute Andrew's queries, so he asks you to help him. Help Dima.
Input Specification:
The first line contains three integers *n*, *m*, *q* (1<=β€<=*n*<=β€<=3Β·105; 0<=β€<=*m*<=<<=*n*; 1<=β€<=*q*<=β€<=3Β·105) β the number of cities, the number of the roads we already have and the number of queries, correspondingly.
Each of the following *m* lines contains two integers, *a**i* and *b**i* (*a**i*<=β <=*b**i*; 1<=β€<=*a**i*,<=*b**i*<=β€<=*n*). These numbers represent the road between cities *a**i* and *b**i*. There can be at most one road between two cities.
Each of the following *q* lines contains one of the two events in the following format:
- 1 *x**i*. It is the request Andrew gives to Dima to find the length of the maximum path in the region that contains city *x**i* (1<=β€<=*x**i*<=β€<=*n*). 2 *x**i* *y**i*. It is the request Andrew gives to Dima to merge the region that contains city *x**i* and the region that contains city *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=*n*). Note, that *x**i* can be equal to *y**i*.
Output Specification:
For each event of the first type print the answer on a separate line.
Demo Input:
['6 0 6\n2 1 2\n2 3 4\n2 5 6\n2 3 2\n2 5 3\n1 1\n']
Demo Output:
['4\n']
Note:
none | 1,449 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of *n* nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly *k* of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input Specification:
The first line contains two integers *n* and *k* (3<=β€<=*n*<=β€<=2Β·105, 2<=β€<=*k*<=β€<=*n*<=-<=1)Β β the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with *n* nodes and *k* exit-nodes within the given constraints.
Output Specification:
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next *n*<=-<=1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to *n*. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Demo Input:
['3 2\n', '5 3\n']
Demo Output:
['2\n1 2\n2 3\n', '3\n1 2\n2 3\n3 4\n3 5\n']
Note:
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted. | 1,450 |
Title: Breaking Good
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.
Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of *n* cities with *m* bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads.
The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.
The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city *n*. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.
First of all the path which they are going to use on their way back from city 1 to their headquarters *n* must be as short as possible, since it is important to finish operation as fast as possible.
Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional.
If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.
Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).
Can you help Walter complete his task and gain the gang's trust?
Input Specification:
The first line of input contains two integers *n*,<=*m* (2<=β€<=*n*<=β€<=105, ), the number of cities and number of roads respectively.
In following *m* lines there are descriptions of roads. Each description consists of three integers *x*,<=*y*,<=*z* (1<=β€<=*x*,<=*y*<=β€<=*n*, ) meaning that there is a road connecting cities number *x* and *y*. If *z*<==<=1, this road is working, otherwise it is not.
Output Specification:
In the first line output one integer *k*, the minimum possible number of roads affected by gang.
In the following *k* lines output three integers describing roads that should be affected. Each line should contain three integers *x*,<=*y*,<=*z* (1<=β€<=*x*,<=*y*<=β€<=*n*, ), cities connected by a road and the new state of a road. *z*<==<=1 indicates that the road between cities *x* and *y* should be repaired and *z*<==<=0 means that road should be blown up.
You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from *z*.
After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and *n*.
If there are multiple optimal answers output any.
Demo Input:
['2 1\n1 2 0\n', '4 4\n1 2 1\n1 3 0\n2 3 1\n3 4 1\n', '8 9\n1 2 0\n8 3 0\n2 3 1\n1 4 1\n8 7 0\n1 5 1\n4 6 1\n5 7 0\n6 8 0\n']
Demo Output:
['1\n1 2 1\n', '3\n1 2 0\n1 3 1\n2 3 0\n', '3\n2 3 0\n1 5 0\n6 8 1\n']
Note:
In the first test the only path is 1β-β2
In the second test the only shortest path is 1β-β3β-β4
In the third test there are multiple shortest paths but the optimal is 1β-β4β-β6β-β8 | 1,451 |
Title: Tavas on the Path
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Tavas lives in Tavaspolis. Tavaspolis has *n* cities numbered from 1 to *n* connected by *n*<=-<=1 bidirectional roads. There exists a path between any two cities. Also each road has a length.
Tavas' favorite strings are binary strings (they contain only 0 and 1). For any binary string like *s*<==<=*s*1*s*2... *s**k*, *T*(*s*) is its *Goodness*. *T*(*s*) can be calculated as follows:
Consider there are exactly *m* blocks of 1s in this string (a block of 1s in *s* is a maximal consecutive substring of *s* that only contains 1) with lengths *x*1,<=*x*2,<=...,<=*x**m*.
Define where *f* is a given sequence (if *m*<==<=0, then *T*(*s*)<==<=0).
Tavas loves queries. He asks you to answer *q* queries. In each query he gives you numbers *v*,<=*u*,<=*l* and you should print following number:
Consider the roads on the path from city *v* to city *u*: *e*1,<=*e*2,<=...,<=*e**x*.
Build the binary string *b* of length *x* such that: *b**i*<==<=1 if and only if *l*<=β€<=*w*(*e**i*) where *w*(*e*) is the length of road *e*.
You should print *T*(*b*) for this query.
Input Specification:
The first line of input contains integers *n* and *q* (2<=β€<=*n*<=β€<=105 and 1<=β€<=*q*<=β€<=105).
The next line contains *n*<=-<=1 space separated integers *f*1,<=*f*2,<=...,<=*f**n*<=-<=1 (|*f**i*|<=β€<=1000).
The next *n*<=-<=1 lines contain the details of the roads. Each line contains integers *v*,<=*u* and *w* and it means that there's a road between cities *v* and *u* of length *w* (1<=β€<=*v*,<=*u*<=β€<=*n* and 1<=β€<=*w*<=β€<=109).
The next *q* lines contain the details of the queries. Each line contains integers *v*,<=*u*,<=*l* (1<=β€<=*v*,<=*u*<=β€<=*n*, *v*<=β <=*u* and 1<=β€<=*l*<=β€<=109).
Output Specification:
Print the answer of each query in a single line.
Demo Input:
['2 3\n10\n1 2 3\n1 2 2\n1 2 3\n1 2 4\n', '6 6\n-5 0 0 2 10\n1 2 1\n2 3 2\n3 4 5\n4 5 1\n5 6 5\n1 6 1\n1 6 2\n1 6 5\n3 6 5\n4 6 4\n1 4 2\n']
Demo Output:
['10\n10\n0\n', '10\n-5\n-10\n-10\n-5\n0\n']
Note:
none | 1,452 |
Title: Duff and Weight Lifting
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of *i*-th of them is 2*w**i* pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps.
Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2*a*1,<=...,<=2*a**k* if and only if there exists a non-negative integer *x* such that 2*a*1<=+<=2*a*2<=+<=...<=+<=2*a**k*<==<=2*x*, i. e. the sum of those numbers is a power of two.
Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps.
Input Specification:
The first line of input contains integer *n* (1<=β€<=*n*<=β€<=106), the number of weights.
The second line contains *n* integers *w*1,<=...,<=*w**n* separated by spaces (0<=β€<=*w**i*<=β€<=106 for each 1<=β€<=*i*<=β€<=*n*), the powers of two forming the weights values.
Output Specification:
Print the minimum number of steps in a single line.
Demo Input:
['5\n1 1 2 3 3\n', '4\n0 1 2 3\n']
Demo Output:
['2\n', '4\n']
Note:
In the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.
In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two. | 1,453 |
Title: Stripe 2
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input Specification:
The first input line contains integer *n* (1<=β€<=*n*<=β€<=105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output Specification:
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Demo Input:
['4\n1 2 3 3\n', '5\n1 2 3 4 5\n']
Demo Output:
['1\n', '0\n']
Note:
none | 1,454 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a matrix consisting of digits zero and one, its size is *n*<=Γ<=*m*. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations?
Let's assume that the rows of matrix *a* are numbered from 1 to *n* from top to bottom and the columns are numbered from 1 to *m* from left to right. A matrix cell on the intersection of the *i*-th row and the *j*-th column can be represented as (*i*,<=*j*). Formally, a submatrix of matrix *a* is a group of four integers *d*,<=*u*,<=*l*,<=*r* (1<=β€<=*d*<=β€<=*u*<=β€<=*n*;Β 1<=β€<=*l*<=β€<=*r*<=β€<=*m*). We will assume that the submatrix contains cells (*i*,<=*j*) (*d*<=β€<=*i*<=β€<=*u*;Β *l*<=β€<=*j*<=β€<=*r*). The area of the submatrix is the number of cells it contains.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=5000). Next *n* lines contain *m* characters each β matrix *a*. Matrix *a* only contains characters: "0" and "1". Note that the elements of the matrix follow without any spaces in the lines.
Output Specification:
Print a single integer β the area of the maximum obtained submatrix. If we cannot obtain a matrix of numbers one, print 0.
Demo Input:
['1 1\n1\n', '2 2\n10\n11\n', '4 3\n100\n011\n000\n101\n']
Demo Output:
['1\n', '2\n', '2\n']
Note:
none | 1,455 |
Title: Crosses
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a board with a grid consisting of *n* rows and *m* columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number *i* and column number *j* as (*i*,<=*j*).
A group of six numbers (*a*,<=*b*,<=*c*,<=*d*,<=*x*0,<=*y*0), where 0<=β€<=*a*,<=*b*,<=*c*,<=*d*, is a cross, and there is a set of cells that are assigned to it. Cell (*x*,<=*y*) belongs to this set if at least one of two conditions are fulfilled:
- |*x*0<=-<=*x*|<=β€<=*a* and |*y*0<=-<=*y*|<=β€<=*b* - |*x*0<=-<=*x*|<=β€<=*c* and |*y*0<=-<=*y*|<=β€<=*d*
Your task is to find the number of different groups of six numbers, (*a*,<=*b*,<=*c*,<=*d*,<=*x*0,<=*y*0) that determine the crosses of an area equal to *s*, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell (*x*,<=*y*) of the cross 1<=β€<=*x*<=β€<=*n*;Β 1<=β€<=*y*<=β€<=*m* holds). The area of the cross is the number of cells it has.
Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points.
Input Specification:
The input consists of a single line containing three integers *n*, *m* and *s* (1<=β€<=*n*,<=*m*<=β€<=500, 1<=β€<=*s*<=β€<=*n*Β·*m*). The integers are separated by a space.
Output Specification:
Print a single integer β the number of distinct groups of six integers that denote crosses with area *s* and that are fully placed on the *n*<=Γ<=*m* grid.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Demo Input:
['2 2 1\n', '3 4 5\n']
Demo Output:
['4\n', '4\n']
Note:
In the first sample the sought groups of six numbers are: (0,β0,β0,β0,β1,β1), (0,β0,β0,β0,β1,β2), (0,β0,β0,β0,β2,β1), (0,β0,β0,β0,β2,β2).
In the second sample the sought groups of six numbers are: (0,β1,β1,β0,β2,β2), (0,β1,β1,β0,β2,β3), (1,β0,β0,β1,β2,β2), (1,β0,β0,β1,β2,β3). | 1,456 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A year ago on the bench in public park Leha found an array of *n* numbers. Leha believes that permutation *p* is right if for all 1<=β€<=*i*<=<<=*n* condition, that *a**p**i*Β·*a**p**i*<=+<=1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109<=+<=7.
Input Specification:
First line of input data contains single integer *n* (1<=β€<=*n*<=β€<=300) β length of the array.
Next line contains *n* integers *a*1,<=*a*2,<=... ,<=*a**n* (1<=β€<=*a**i*<=β€<=109) β found array.
Output Specification:
Output single integer β number of right permutations modulo 109<=+<=7.
Demo Input:
['3\n1 2 4\n', '7\n5 2 4 2 4 1 1\n']
Demo Output:
['2\n', '144\n']
Note:
For first example:
[1,β2,β4] β right permutation, because 2 and 8 are not perfect squares.
[1,β4,β2] β wrong permutation, because 4 is square of 2.
[2,β1,β4] β wrong permutation, because 4 is square of 2.
[2,β4,β1] β wrong permutation, because 4 is square of 2.
[4,β1,β2] β wrong permutation, because 4 is square of 2.
[4,β2,β1] β right permutation, because 8 and 2 are not perfect squares. | 1,457 |
Title: Chat
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are times you recall a good old friend and everything you've come through together. Luckily there are social networksΒ β they store all your message history making it easy to know what you argued over 10 years ago.
More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to *n* where *n* is the total number of messages in the chat.
Each message might contain a link to an earlier message which it is a reply to. When opening a message *x* or getting a link to it, the dialogue is shown in such a way that *k* previous messages, message *x* and *k* next messages are visible (with respect to message *x*). In case there are less than *k* messages somewhere, they are yet all shown.
Digging deep into your message history, you always read all visible messages and then go by the link in the current message *x* (if there is one) and continue reading in the same manner.
Determine the number of messages you'll read if your start from message number *t* for all *t* from 1 to *n*. Calculate these numbers independently. If you start with message *x*, the initial configuration is *x* itself, *k* previous and *k* next messages. Messages read multiple times are considered as one.
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*n*<=β€<=105, 0<=β€<=*k*<=β€<=*n*) β the total amount of messages and the number of previous and next messages visible.
The second line features a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=<<=*i*), where *a**i* denotes the *i*-th message link destination or zero, if there's no link from *i*. All messages are listed in chronological order. It's guaranteed that the link from message *x* goes to message with number strictly less than *x*.
Output Specification:
Print *n* integers with *i*-th denoting the number of distinct messages you can read starting from message *i* and traversing the links while possible.
Demo Input:
['6 0\n0 1 1 2 3 2\n', '10 1\n0 1 0 3 4 5 2 3 7 0\n', '2 2\n0 1\n']
Demo Output:
['1 2 2 3 3 3 \n', '2 3 3 4 5 6 6 6 8 2 \n', '2 2 \n']
Note:
Consider *i*β=β6 in sample case one. You will read message 6, then 2, then 1 and then there will be no link to go.
In the second sample case *i*β=β6 gives you messages 5,β6,β7 since *k*β=β1, then 4,β5,β6, then 2,β3,β4 and then the link sequence breaks. The number of distinct messages here is equal to 6. | 1,458 |
Title: Superior Periodic Subarrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an infinite periodic array *a*0,<=*a*1,<=...,<=*a**n*<=-<=1,<=... with the period of length *n*. Formally, . A periodic subarray (*l*,<=*s*) (0<=β€<=*l*<=<<=*n*, 1<=β€<=*s*<=<<=*n*) of array *a* is an infinite periodic array with a period of length *s* that is a subsegment of array *a*, starting with position *l*.
A periodic subarray (*l*,<=*s*) is superior, if when attaching it to the array *a*, starting from index *l*, any element of the subarray is larger than or equal to the corresponding element of array *a*. An example of attaching is given on the figure (top β infinite array *a*, bottom β its periodic subarray (*l*,<=*s*)):
Find the number of distinct pairs (*l*,<=*s*), corresponding to the superior periodic arrays.
Input Specification:
The first line contains number *n* (1<=β€<=*n*<=β€<=2Β·105). The second line contains *n* numbers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1 (1<=β€<=*a**i*<=β€<=106), separated by a space.
Output Specification:
Print a single integer β the sought number of pairs.
Demo Input:
['4\n7 1 2 3\n', '2\n2 1\n', '3\n1 1 1\n']
Demo Output:
['2\n', '1\n', '6\n']
Note:
In the first sample the superior subarrays are (0, 1) and (3, 2).
Subarray (0, 1) is superior, as *a*<sub class="lower-index">0</sub>ββ₯β*a*<sub class="lower-index">0</sub>,β*a*<sub class="lower-index">0</sub>ββ₯β*a*<sub class="lower-index">1</sub>,β*a*<sub class="lower-index">0</sub>ββ₯β*a*<sub class="lower-index">2</sub>,β*a*<sub class="lower-index">0</sub>ββ₯β*a*<sub class="lower-index">3</sub>,β*a*<sub class="lower-index">0</sub>ββ₯β*a*<sub class="lower-index">0</sub>,β...
Subarray (3, 2) is superior *a*<sub class="lower-index">3</sub>ββ₯β*a*<sub class="lower-index">3</sub>,β*a*<sub class="lower-index">0</sub>ββ₯β*a*<sub class="lower-index">0</sub>,β*a*<sub class="lower-index">3</sub>ββ₯β*a*<sub class="lower-index">1</sub>,β*a*<sub class="lower-index">0</sub>ββ₯β*a*<sub class="lower-index">2</sub>,β*a*<sub class="lower-index">3</sub>ββ₯β*a*<sub class="lower-index">3</sub>,β...
In the third sample any pair of (*l*,β*s*) corresponds to a superior subarray as all the elements of an array are distinct. | 1,459 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Fox Ciel is playing a card game with her friend Fox Jiro. There are *n* piles of cards on the table. And there is a positive integer on each card.
The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.
Suppose Ciel and Jiro play optimally, what is the score of the game?
Input Specification:
The first line contain an integer *n* (1<=β€<=*n*<=β€<=100). Each of the next *n* lines contains a description of the pile: the first integer in the line is *s**i* (1<=β€<=*s**i*<=β€<=100) β the number of cards in the *i*-th pile; then follow *s**i* positive integers *c*1, *c*2, ..., *c**k*, ..., *c**s**i* (1<=β€<=*c**k*<=β€<=1000) β the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.
Output Specification:
Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.
Demo Input:
['2\n1 100\n2 1 10\n', '1\n9 2 8 6 5 9 4 7 1 3\n', '3\n3 1 3 2\n3 5 4 6\n2 8 7\n', '3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000\n']
Demo Output:
['101 10\n', '30 15\n', '18 18\n', '7000 7000\n']
Note:
In the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10.
In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3. | 1,460 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.
Consider two dices. When thrown each dice shows some integer from 1 to *n* inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and different dices may have different probability distributions.
We throw both dices simultaneously and then calculate values *max*(*a*,<=*b*) and *min*(*a*,<=*b*), where *a* is equal to the outcome of the first dice, while *b* is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for *max*(*a*,<=*b*) and *min*(*a*,<=*b*). That is, for each *x* from 1 to *n* you know the probability that *max*(*a*,<=*b*) would be equal to *x* and the probability that *min*(*a*,<=*b*) would be equal to *x*. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists.
Input Specification:
First line contains the integer *n* (1<=β€<=*n*<=β€<=100<=000)Β β the number of different values for both dices.
Second line contains an array consisting of *n* real values with up to 8 digits after the decimal point Β β probability distribution for *max*(*a*,<=*b*), the *i*-th of these values equals to the probability that *max*(*a*,<=*b*)<==<=*i*. It's guaranteed that the sum of these values for one dice is 1. The third line contains the description of the distribution *min*(*a*,<=*b*) in the same format.
Output Specification:
Output two descriptions of the probability distribution for *a* on the first line and for *b* on the second line.
The answer will be considered correct if each value of max(*a*,<=*b*) and min(*a*,<=*b*) probability distribution values does not differ by more than 10<=-<=6 from ones given in input. Also, probabilities should be non-negative and their sums should differ from 1 by no more than 10<=-<=6.
Demo Input:
['2\n0.25 0.75\n0.75 0.25\n', '3\n0.125 0.25 0.625\n0.625 0.25 0.125\n']
Demo Output:
['0.5 0.5 \n0.5 0.5 \n', '0.25 0.25 0.5 \n0.5 0.25 0.25 \n']
Note:
none | 1,461 |
Title: World Eater Brothers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world.
As you know there are *n* countries in the world. These countries are connected by *n*<=-<=1 directed roads. If you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once.
Each of the brothers wants to establish his reign in some country, then it's possible for him to control the countries that can be reached from his country using directed roads.
The brothers can rule the world if there exists at most two countries for brothers to choose (and establish their reign in these countries) so that any other country is under control of at least one of them. In order to make this possible they want to change the direction of minimum number of roads. Your task is to calculate this minimum number of roads.
Input Specification:
The first line of input contains an integer *n* (1<=β€<=*n*<=β€<=3000). Each of the next *n*<=-<=1 lines contains two space-separated integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*;Β *a**i*<=β <=*b**i*) saying there is a road from country *a**i* to country *b**i*.
Consider that countries are numbered from 1 to *n*. It's guaranteed that if you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once.
Output Specification:
In the only line of output print the minimum number of roads that their direction should be changed so that the brothers will be able to rule the world.
Demo Input:
['4\n2 1\n3 1\n4 1\n', '5\n2 1\n2 3\n4 3\n4 5\n']
Demo Output:
['1\n', '0\n']
Note:
none | 1,462 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Andrey needs one more problem to conduct a programming contest. He has *n* friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends β the probability that this friend will come up with a problem if Andrey asks him.
Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=100) β the number of Andrey's friends. The second line contains *n* real numbers *p**i* (0.0<=β€<=*p**i*<=β€<=1.0) β the probability that the *i*-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.
Output Specification:
Print a single real number β the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10<=-<=9.
Demo Input:
['4\n0.1 0.2 0.3 0.8\n', '2\n0.1 0.2\n']
Demo Output:
['0.800000000000\n', '0.260000000000\n']
Note:
In the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.
In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1Β·0.8β+β0.9Β·0.2β=β0.26. | 1,463 |
Title: Chess Championship
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ostap is preparing to play chess again and this time he is about to prepare. Thus, he was closely monitoring one recent chess tournament. There were *m* players participating and each pair of players played exactly one game. The victory gives 2 points, drawΒ β 1 points, loseΒ β 0 points.
Ostap is lazy, so he never tries to remember the outcome of each game. Instead, he computes the total number of points earned by each of the players (the sum of his points in all games which he took part in), sort these value in non-ascending order and then remembers first *n* integers in this list.
Now the Great Strategist Ostap wonders whether he remembers everything correct. He considers that he is correct if there exists at least one tournament results table such that it will produce the given integers. That means, if we count the sum of points for each player, sort them and take first *n* elements, the result will coincide with what Ostap remembers. Can you check if such table exists?
Input Specification:
The first line of the input contains two integers *m* and *n* (1<=β€<=*n*<=β€<=*m*<=β€<=3000)Β β the number of participants of the tournament and the number of top results Ostap remembers.
The second line contains *n* integers, provided in non-ascending orderΒ β the number of points earned by top participants as Ostap remembers them. It's guaranteed that this integers are non-negative and do not exceed 2Β·*m*.
Output Specification:
If there is no tournament such that Ostap can obtain the given set of integers using the procedure described in the statement, then print "no" in the only line of the output. Otherwise, the first line of the output should contain the word "yes". Next *m* lines should provide the description of any valid tournament. Each of these lines must contain *m* characters 'X', 'W', 'D' and 'L'. Character 'X' should always be located on the main diagonal (and only there), that is on the *i*-th position of the *i*-th string. Character 'W' on the *j*-th position of the *i*-th string means that the *i*-th player won the game against the *j*-th. In the same way character 'L' means loose and 'D' means draw.
The table you print must be consistent and the points earned by best *n* participants should match the memory of Ostap. If there are many possible answers, print any of them.
Demo Input:
['5 5\n8 6 4 2 0\n', '5 1\n9\n']
Demo Output:
['yes\nXWWWW\nLXWWW\nLLXWW\nLLLXW\nLLLLX\n', 'no\n']
Note:
none | 1,464 |
Title: Permute Digits
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0.
It is allowed to leave *a* as it is.
Input Specification:
The first line contains integer *a* (1<=β€<=*a*<=β€<=1018). The second line contains integer *b* (1<=β€<=*b*<=β€<=1018). Numbers don't have leading zeroes. It is guaranteed that answer exists.
Output Specification:
Print the maximum possible number that is a permutation of digits of *a* and is not greater than *b*. The answer can't have any leading zeroes. It is guaranteed that the answer exists.
The number in the output should have exactly the same length as number *a*. It should be a permutation of digits of *a*.
Demo Input:
['123\n222\n', '3921\n10000\n', '4940\n5000\n']
Demo Output:
['213\n', '9321\n', '4940\n']
Note:
none | 1,465 |
Title: A Mist of Florescence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"I've been here once," Mino exclaims with delight, "it's breathtakingly amazing."
"What is it like?"
"Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?"
There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses.
The wood can be represented by a rectangular grid of $n$ rows and $m$ columns. In each cell of the grid, there is exactly one type of flowers.
According to Mino, the numbers of connected components formed by each kind of flowers are $a$, $b$, $c$ and $d$ respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers.
You are to help Kanno depict such a grid of flowers, with $n$ and $m$ arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem.
Note that you can choose arbitrary $n$ and $m$ under the constraints below, they are not given in the input.
Input Specification:
The first and only line of input contains four space-separated integers $a$, $b$, $c$ and $d$ ($1 \leq a, b, c, d \leq 100$)Β β the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively.
Output Specification:
In the first line, output two space-separated integers $n$ and $m$ ($1 \leq n, m \leq 50$)Β β the number of rows and the number of columns in the grid respectively.
Then output $n$ lines each consisting of $m$ consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively.
In case there are multiple solutions, print any. You can output each letter in either case (upper or lower).
Demo Input:
['5 3 2 1\n', '50 50 1 1\n', '1 6 4 5\n']
Demo Output:
['4 7\nDDDDDDD\nDABACAD\nDBABACD\nDDDDDDD', '4 50\nCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\nABABABABABABABABABABABABABABABABABABABABABABABABAB\nBABABABABABABABABABABABABABABABABABABABABABABABABA\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD', '7 7\nDDDDDDD\nDDDBDBD\nDDCDCDD\nDBDADBD\nDDCDCDD\nDBDBDDD\nDDDDDDD']
Note:
In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. | 1,466 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As we all know, Dart is some kind of creature from Upside Down world. For simplicity, we call their kind pollywogs. Dart and *x*<=-<=1 other pollywogs are playing a game. There are *n* stones in a row, numbered from 1 through *n* from left to right. At most 1 pollywog may be sitting on each stone at a time. Initially, the pollywogs are sitting on the first *x* stones (one pollywog on each stone).
Dart and his friends want to end up on the last *x* stones. At each second, the leftmost pollywog should jump to the right. A pollywog can jump at most *k* stones; more specifically, a pollywog can jump from stone number *i* to stones *i*<=+<=1,<=*i*<=+<=2,<=... *i*<=+<=*k*. A pollywog can't jump on an occupied stone. Jumping a distance *i* takes *c**i* amounts of energy from the pollywog.
Also, *q* stones are special Each time landing on a special stone *p*, takes *w**p* amounts of energy (in addition to the energy for jump) from the pollywog. *w**p* could be negative, in this case, it means the pollywog absorbs |*w**p*| amounts of energy.
Pollywogs want to spend as little energy as possible (this value could be negative).
They're just pollywogs, so they asked for your help. Tell them the total change in their energy, in case they move optimally.
Input Specification:
The first line of input contains four integers, *x*,<=*k*,<=*n* and *q* (1<=β€<=*x*<=β€<=*k*<=β€<=8, *k*<=β€<=*n*<=β€<=108, 0<=β€<=*q*<=β€<=*min*(25,<=*n*<=-<=*x*))Β β the number of pollywogs, the maximum length of jump, the number of stones and the number of special stones.
The next line contains *k* integers, *c*1,<=*c*2,<=... *c**k*, separated by spaces (1<=β€<=*c**i*<=β€<=109)Β β the energetic costs of jumps.
The next *q* lines contain description of the special stones. Each line contains two integers *p* and *w**p* (*x*<=+<=1<=β€<=*p*<=β€<=*n*, |*w**p*|<=β€<=109). All *p* are distinct.
Output Specification:
Print the minimum amount of energy they need, in the first and only line of output.
Demo Input:
['2 3 10 2\n1 2 3\n5 -10\n6 1000\n', '4 7 85 3\n17 5 28 4 52 46 6\n59 -76\n33 -69\n19 2018\n']
Demo Output:
['6\n', '135\n']
Note:
none | 1,467 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a straight line colored in white. *n* black segments are added on it one by one.
After each segment is added, determine the number of connected components of black segments (i.Β e. the number of black segments in the union of the black segments).
In particular, if one segment ends in a point *x*, and another segment starts in the point *x*, these two segments belong to the same connected component.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=200<=000) β the number of segments.
The *i*-th of the next *n* lines contains two integers *l**i* and *r**i* (1<=β€<=*l**i*<=<<=*r**i*<=β€<=109) β the coordinates of the left and the right ends of the *i*-th segment. The segments are listed in the order they are added on the white line.
Output Specification:
Print *n* integers β the number of connected components of black segments after each segment is added.
Demo Input:
['3\n1 3\n4 5\n2 4\n', '9\n10 20\n50 60\n30 40\n70 80\n90 100\n60 70\n10 40\n40 50\n80 90\n']
Demo Output:
['1 2 1 \n', '1 2 3 4 5 4 3 2 1 \n']
Note:
In the first example there are two components after the addition of the first two segments, because these segments do not intersect. The third added segment intersects the left segment and touches the right segment at the point 4 (these segments belong to the same component, according to the statements). Thus the number of connected components of black segments is equal to 1 after that. | 1,468 |
Title: Sequence of Balls
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
You are given a sequence of balls *A* by your teacher, each labeled with a lowercase Latin letter 'a'-'z'. You don't like the given sequence. You want to change it into a new sequence, *B* that suits you better. So, you allow yourself four operations:
- You can insert any ball with any label into the sequence at any position. - You can delete (remove) any ball from any position. - You can replace any ball with any other ball. - You can exchange (swap) two adjacent balls.
Your teacher now places time constraints on each operation, meaning that an operation can only be performed in certain time. So, the first operation takes time *t**i*, the second one takes *t**d*, the third one takes *t**r* and the fourth one takes *t**e*. Also, it is given that 2Β·*t**e*<=β₯<=*t**i*<=+<=*t**d*.
Find the minimal time to convert the sequence *A* to the sequence *B*.
Input Specification:
The first line contains four space-separated integers *t**i*,<=*t**d*,<=*t**r*,<=*t**e* (0<=<<=*t**i*,<=*t**d*,<=*t**r*,<=*t**e*<=β€<=100). The following two lines contain sequences *A* and *B* on separate lines. The length of each line is between 1 and 4000 characters inclusive.
Output Specification:
Print a single integer representing minimum time to convert *A* into *B*.
Demo Input:
['1 1 1 1\nyoushouldnot\nthoushaltnot\n', '2 4 10 3\nab\nba\n', '1 10 20 30\na\nza\n']
Demo Output:
['5\n', '3\n', '1\n']
Note:
In the second sample, you could delete the ball labeled 'a' from the first position and then insert another 'a' at the new second position with total time 6. However exchanging the balls give total time 3. | 1,469 |
Title: Cactus
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle.
A simple cycle in a undirected graph is a sequence of distinct vertices *v*1,<=*v*2,<=...,<=*v**t* (*t*<=><=2), such that for any *i* (1<=β€<=*i*<=<<=*t*) exists an edge between vertices *v**i* and *v**i*<=+<=1, and also exists an edge between vertices *v*1 and *v**t*.
A simple path in a undirected graph is a sequence of not necessarily distinct vertices *v*1,<=*v*2,<=...,<=*v**t* (*t*<=><=0), such that for any *i* (1<=β€<=*i*<=<<=*t*) exists an edge between vertices *v**i* and *v**i*<=+<=1 and furthermore each edge occurs no more than once. We'll say that a simple path *v*1,<=*v*2,<=...,<=*v**t* starts at vertex *v*1 and ends at vertex *v**t*.
You've got a graph consisting of *n* vertices and *m* edges, that is a vertex cactus. Also, you've got a list of *k* pairs of interesting vertices *x**i*,<=*y**i*, for which you want to know the following information β the number of distinct simple paths that start at vertex *x**i* and end at vertex *y**i*. We will consider two simple paths distinct if the sets of edges of the paths are distinct.
For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo 1000000007 (109<=+<=7).
Input Specification:
The first line contains two space-separated integers *n*,<=*m* (2<=β€<=*n*<=β€<=105;Β 1<=β€<=*m*<=β€<=105) β the number of vertices and edges in the graph, correspondingly. Next *m* lines contain the description of the edges: the *i*-th line contains two space-separated integers *a**i*,<=*b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*) β the indexes of the vertices connected by the *i*-th edge.
The next line contains a single integer *k* (1<=β€<=*k*<=β€<=105) β the number of pairs of interesting vertices. Next *k* lines contain the list of pairs of interesting vertices: the *i*-th line contains two space-separated numbers *x**i*, *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=*n*;Β *x**i*<=β <=*y**i*) β the indexes of interesting vertices in the *i*-th pair.
It is guaranteed that the given graph is a vertex cactus. It is guaranteed that the graph contains no loops or multiple edges. Consider the graph vertices are numbered from 1 to *n*.
Output Specification:
Print *k* lines: in the *i*-th line print a single integer β the number of distinct simple ways, starting at *x**i* and ending at *y**i*, modulo 1000000007 (109<=+<=7).
Demo Input:
['10 11\n1 2\n2 3\n3 4\n1 4\n3 5\n5 6\n8 6\n8 7\n7 6\n7 9\n9 10\n6\n1 2\n3 5\n6 9\n9 2\n9 3\n9 10\n']
Demo Output:
['2\n2\n2\n4\n4\n1\n']
Note:
none | 1,470 |
Title: Perun, Ult!
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A lot of students spend their winter holidays productively. Vlad has advanced very well in doing so! For three days already, fueled by salads and tangerinesΒ β the leftovers from New Year celebrationΒ β he has been calibrating his rating in his favorite MOBA game, playing as a hero named Perun.
Perun has an ultimate ability called "Thunderwrath". At the instant of its activation, each enemy on the map (*n* of them in total) loses health points as a single-time effect. It also has a restriction: it can only activated when the moment of time is an integer. The initial bounty for killing an enemy is . Additionally, it increases by each second. Formally, if at some second *t* the ability is activated and the *i*-th enemy is killed as a result (i.e. his health drops to zero or lower), Vlad earns units of gold.
Every enemy can receive damage, as well as be healed. There are multiple ways of doing so, but Vlad is not interested in details. For each of *n* enemies he knows:
- Β β maximum number of health points for the *i*-th enemy; - Β β initial health of the enemy (on the 0-th second); - Β β the amount of health the *i*-th enemy can regenerate per second.
There also *m* health updates Vlad knows about:
- Β β time when the health was updated; - Β β the enemy whose health was updated; - Β β updated health points for *enemy**j*.
Obviously, Vlad wants to maximize his profit. If it's necessary, he could even wait for years to activate his ability at the right second. Help him determine the exact second (note that it must be an integer) from 0 (inclusively) to <=+<=β so that a single activation of the ability would yield Vlad the maximum possible amount of gold, and print this amount.
Input Specification:
In the first line, two integers are given (separated by spaces)Β β *n* and *m* (1<=β€<=*n*<=β€<=105, 0<=β€<=*m*<=β€<=105).
In the second line, there are three integers: , and (, ).
Each of the following *n* lines has three integersΒ β , , (, ).
The next *m* lines contain three integers eachΒ β , , (, , ). It is guaranteed that there is no more than one hearth change per second for each enemy: more formally, for each *a*,<=*b* so that 1<=β€<=*a*,<=*b*<=β€<=*m*,<=*a*<=β <=*b* holds that if , then .
Output Specification:
Output the single integerΒ β the maximum amount of gold Vlad can obtain if he applies "Thunderwrath" exactly once, or -1 if this amount can be infinitely large.
Demo Input:
['3 2\n1000 10 50\n70 5 5\n90 70 1\n110 20 2\n20 2 10\n30 3 10\n', '1 1\n500 50 1000\n750 750 20\n10 1 300\n']
Demo Output:
['3000\n', '-1\n']
Note:
On the pictures you can see health points of each enemy versus time in sample cases.
Periods when Vlad can kill one enemy are marked with yellow color.
Periods when Vlad can kill two enemies are marked with purple color.
In the first sample case, Vlad can activate the ability at the 50-th second: the enemies 2 and 3 will die since they would have 40 and 50 health points correspondingly. Vlad will earn 2Β·(1000β+β50Β·10)β=β3000 gold.
In the second sample case, the maximum amount of health for the enemy 1 is less than the damage dealt by the ability. Hence, the enemy could be killed anytime. As the bounty increases by 50 over the time, the maximum possible amount of gold is infinite. | 1,471 |
Title: Substitutes in Number
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Andrew and Eugene are playing a game. Initially, Andrew has string *s*, consisting of digits. Eugene sends Andrew multiple queries of type "*d**i*<=β<=*t**i*", that means "replace all digits *d**i* in string *s* with substrings equal to *t**i*". For example, if *s*<==<=123123, then query "2<=β<=00" transforms *s* to 10031003, and query "3<=β<=" ("replace 3 by an empty string") transforms it to *s*<==<=1212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to *s* by 1000000007Β (109<=+<=7). When you represent *s* as a decimal number, please ignore the leading zeroes; also if *s* is an empty string, then it's assumed that the number equals to zero.
Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!
Input Specification:
The first line contains string *s* (1<=β€<=|*s*|<=β€<=105), consisting of digitsΒ β the string before processing all the requests.
The second line contains a single integer *n* (0<=β€<=*n*<=β€<=105)Β β the number of queries.
The next *n* lines contain the descriptions of the queries. The *i*-th query is described by string "*d**i*->*t**i*", where *d**i* is exactly one digit (from 0 to 9), *t**i* is a string consisting of digits (*t**i* can be an empty string). The sum of lengths of *t**i* for all queries doesn't exceed 105. The queries are written in the order in which they need to be performed.
Output Specification:
Print a single integer β remainder of division of the resulting number by 1000000007Β (109<=+<=7).
Demo Input:
['123123\n1\n2->00\n', '123123\n1\n3->\n', '222\n2\n2->0\n0->7\n', '1000000008\n0\n']
Demo Output:
['10031003\n', '1212\n', '777\n', '1\n']
Note:
Note that the leading zeroes are not removed from string *s* after the replacement (you can see it in the third sample). | 1,472 |
Title: Soldier and Bananas
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*Β·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
Input Specification:
The first line contains three positive integers *k*,<=*n*,<=*w* (1<=<=β€<=<=*k*,<=*w*<=<=β€<=<=1000, 0<=β€<=*n*<=β€<=109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.
Output Specification:
Output one integer β the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.
Demo Input:
['3 17 4\n']
Demo Output:
['13']
Note:
none | 1,473 |
Title: Birthday
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. *n* friends came by, and after a typical party they decided to play blind man's buff.
The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several rounds. In each round, Misha catches exactly one of his friends and has to guess who it is. The probability of catching the *i*-th friend does not change between rounds and is equal to *p**i* percent (as we know, it is directly proportional to the amount of alcohol consumed by the *i*-th friend) and *p*1<=+<=*p*2<=+<=...<=+<=*p**n*<==<=100 holds. Misha has no information about who he caught. After Misha makes an attempt to guess the caught person, the round ends. Even then, Misha isn't told whether he guessed correctly, and a new round begins.
The game ends when Misha guesses every friend at least once, that is, there exists such set of rounds *k*1,<=*k*2,<=...,<=*k**n*, that during round number *k**i* Misha caught the *i*-th friend and guessed him. Misha wants to minimize the expectation of the number of rounds of the game. Despite the fact that at any point in the game Misha has no information about who he has already guessed, his friends are honest, and if they see that the condition for the end of the game is fulfilled, the game ends immediately. Find the expectation of the number of rounds in the game if Misha plays optimally.
Input Specification:
The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=100)Β β the number of Misha's friends.
The second line contains *n* integers *p**i* (), giving the probability to catch the *i*-th friend in one particular round in percent.
Output Specification:
Print a single real valueΒ β the expectation of the number of rounds provided that Misha plays optimally. Your answer will be considered correct if its absolute or relative 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 .
Demo Input:
['2\n50 50\n', '4\n50 20 20 10\n']
Demo Output:
['5.0000000000\n', '39.2846263444\n']
Note:
The optimal strategy in the first sample is to guess friends alternately. | 1,474 |
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size *n*<=Γ<=*m*, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.
Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100) Β β the size of the table.
Output Specification:
Print the table that meets the condition: *n* lines containing *m* integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer.
Demo Input:
['1 1\n', '1 2\n']
Demo Output:
['1', '3 4']
Note:
none | 1,475 |
Title: Little Elephant and Chess
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Little Elephant loves chess very much.
One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8<=Γ<=8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doesn't have any side-adjacent cells with the same color and the upper left cell is white. To play chess, they want to make the board they have a proper chessboard. For that the friends can choose any row of the board and cyclically shift the cells of the chosen row, that is, put the last (rightmost) square on the first place in the row and shift the others one position to the right. You can run the described operation multiple times (or not run it at all).
For example, if the first line of the board looks like that "BBBBBBWW" (the white cells of the line are marked with character "W", the black cells are marked with character "B"), then after one cyclic shift it will look like that "WBBBBBBW".
Help the Little Elephant and his friend to find out whether they can use any number of the described operations to turn the board they have into a proper chessboard.
Input Specification:
The input consists of exactly eight lines. Each line contains exactly eight characters "W" or "B" without any spaces: the *j*-th character in the *i*-th line stands for the color of the *j*-th cell of the *i*-th row of the elephants' board. Character "W" stands for the white color, character "B" stands for the black color.
Consider the rows of the board numbered from 1 to 8 from top to bottom, and the columns β from 1 to 8 from left to right. The given board can initially be a proper chessboard.
Output Specification:
In a single line print "YES" (without the quotes), if we can make the board a proper chessboard and "NO" (without the quotes) otherwise.
Demo Input:
['WBWBWBWB\nBWBWBWBW\nBWBWBWBW\nBWBWBWBW\nWBWBWBWB\nWBWBWBWB\nBWBWBWBW\nWBWBWBWB\n', 'WBWBWBWB\nWBWBWBWB\nBBWBWWWB\nBWBWBWBW\nBWBWBWBW\nBWBWBWWW\nBWBWBWBW\nBWBWBWBW\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first sample you should shift the following lines one position to the right: the 3-rd, the 6-th, the 7-th and the 8-th.
In the second sample there is no way you can achieve the goal. | 1,476 |
Title: Cinema Line
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The new "Die Hard" movie has just been released! There are *n* people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=105) β the number of people in the line. The next line contains *n* integers, each of them equals 25, 50 or 100 β the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.
Output Specification:
Print "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".
Demo Input:
['4\n25 25 50 50\n', '2\n25 100\n', '4\n50 50 25 25\n']
Demo Output:
['YES\n', 'NO\n', 'NO\n']
Note:
none | 1,477 |
Title: Hard Process
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* with *n* elements. Each element of *a* is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in *a*, consisting of only numbers one, as *f*(*a*). You can change no more than *k* zeroes to ones to maximize *f*(*a*).
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*n*<=β€<=3Β·105,<=0<=β€<=*k*<=β€<=*n*) β the number of elements in *a* and the parameter *k*.
The second line contains *n* integers *a**i* (0<=β€<=*a**i*<=β€<=1) β the elements of *a*.
Output Specification:
On the first line print a non-negative integer *z* β the maximal value of *f*(*a*) after no more than *k* changes of zeroes to ones.
On the second line print *n* integers *a**j* β the elements of the array *a* after the changes.
If there are multiple answers, you can print any one of them.
Demo Input:
['7 1\n1 0 0 1 1 0 1\n', '10 2\n1 0 0 1 0 1 0 1 0 1\n']
Demo Output:
['4\n1 0 0 1 1 1 1\n', '5\n1 0 0 1 1 1 1 1 0 1\n']
Note:
none | 1,478 |
Title: Anton and Polyhedrons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
- Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
Anton has a collection of *n* polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input Specification:
The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=200<=000)Β β the number of polyhedrons in Anton's collection.
Each of the following *n* lines of the input contains a string *s**i*Β β the name of the *i*-th polyhedron in Anton's collection. The string can look like this:
- "Tetrahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is a tetrahedron. - "Cube" (without quotes), if the *i*-th polyhedron in Anton's collection is a cube. - "Octahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is an octahedron. - "Dodecahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is a dodecahedron. - "Icosahedron" (without quotes), if the *i*-th polyhedron in Anton's collection is an icosahedron.
Output Specification:
Output one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.
Demo Input:
['4\nIcosahedron\nCube\nTetrahedron\nDodecahedron\n', '3\nDodecahedron\nOctahedron\nOctahedron\n']
Demo Output:
['42\n', '28\n']
Note:
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces. | 1,479 |
Title: George and Accommodation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* people living in it and the room can accommodate *q**i* people in total (*p**i*<=β€<=*q**i*). Your task is to count how many rooms has free place for both George and Alex.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=100) β the number of rooms.
The *i*-th of the next *n* lines contains two integers *p**i* and *q**i* (0<=β€<=*p**i*<=β€<=*q**i*<=β€<=100) β the number of people who already live in the *i*-th room and the room's capacity.
Output Specification:
Print a single integer β the number of rooms where George and Alex can move in.
Demo Input:
['3\n1 1\n2 2\n3 3\n', '3\n1 10\n0 10\n10 10\n']
Demo Output:
['0\n', '2\n']
Note:
none | 1,480 |
Title: A Prosperous Lot
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.
Big Banban is hesitating over the amount of money to give out. He considers loops to be lucky since it symbolizes unity and harmony.
He would like to find a positive integer *n* not greater than 1018, such that there are exactly *k* loops in the decimal representation of *n*, or determine that such *n* does not exist.
A loop is a planar area enclosed by lines in the digits' decimal representation written in Arabic numerals. For example, there is one loop in digit 4, two loops in 8 and no loops in 5. Refer to the figure below for all exact forms.
Input Specification:
The first and only line contains an integer *k* (1<=β€<=*k*<=β€<=106)Β β the desired number of loops.
Output Specification:
Output an integerΒ β if no such *n* exists, output -1; otherwise output any such *n*. In the latter case, your output should be a positive decimal integer not exceeding 1018.
Demo Input:
['2\n', '6\n']
Demo Output:
['462', '8080']
Note:
none | 1,481 |
Title: Mr. Kitayuta's Gift
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mr. Kitayuta has kindly given you a string *s* consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into *s* to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.
You can choose any lowercase English letter, and insert it to any position of *s*, possibly to the beginning or the end of *s*. You have to insert a letter even if the given string is already a palindrome.
If it is possible to insert one lowercase English letter into *s* so that the resulting string will be a palindrome, print the string after the insertion. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one palindrome that can be obtained, you are allowed to print any of them.
Input Specification:
The only line of the input contains a string *s* (1<=β€<=|*s*|<=β€<=10). Each character in *s* is a lowercase English letter.
Output Specification:
If it is possible to turn *s* into a palindrome by inserting one lowercase English letter, print the resulting string in a single line. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one solution, any of them will be accepted.
Demo Input:
['revive\n', 'ee\n', 'kitayuta\n']
Demo Output:
['reviver\n', 'eye', 'NA\n']
Note:
For the first sample, insert 'r' to the end of "revive" to obtain a palindrome "reviver".
For the second sample, there is more than one solution. For example, "eve" will also be accepted.
For the third sample, it is not possible to turn "kitayuta" into a palindrome by just inserting one letter. | 1,482 |
Title: Pyramid of Glasses
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is *n*. The top level consists of only 1 glass, that stands on 2 glasses on the second level (counting from the top), then 3 glasses on the third level and so on.The bottom level consists of *n* glasses.
Vlad has seen in the movies many times how the champagne beautifully flows from top levels to bottom ones, filling all the glasses simultaneously. So he took a bottle and started to pour it in the glass located at the top of the pyramid.
Each second, Vlad pours to the top glass the amount of champagne equal to the size of exactly one glass. If the glass is already full, but there is some champagne flowing in it, then it pours over the edge of the glass and is equally distributed over two glasses standing under. If the overflowed glass is at the bottom level, then the champagne pours on the table. For the purpose of this problem we consider that champagne is distributed among pyramid glasses immediately. Vlad is interested in the number of completely full glasses if he stops pouring champagne in *t* seconds.
Pictures below illustrate the pyramid consisting of three levels.
Input Specification:
The only line of the input contains two integers *n* and *t* (1<=β€<=*n*<=β€<=10,<=0<=β€<=*t*<=β€<=10<=000)Β β the height of the pyramid and the number of seconds Vlad will be pouring champagne from the bottle.
Output Specification:
Print the single integerΒ β the number of completely full glasses after *t* seconds.
Demo Input:
['3 5\n', '4 8\n']
Demo Output:
['4\n', '6\n']
Note:
In the first sample, the glasses full after 5 seconds are: the top glass, both glasses on the second level and the middle glass at the bottom level. Left and right glasses of the bottom level will be half-empty. | 1,483 |
Title: Bus of Characters
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.
Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers:
- an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; - an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.
You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.
Input Specification:
The first line contains a single integer $n$ ($1 \le n \le 200\,000$) β the number of rows in the bus.
The second line contains the sequence of integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le 10^{9}$), where $w_i$ is the width of each of the seats in the $i$-th row. It is guaranteed that all $w_i$ are distinct.
The third line contains a string of length $2n$, consisting of digits '0' and '1' β the description of the order the passengers enter the bus. If the $j$-th character is '0', then the passenger that enters the bus on the $j$-th stop is an introvert. If the $j$-th character is '1', the the passenger that enters the bus on the $j$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i.Β e. both numbers equal $n$), and for each extrovert there always is a suitable row.
Output Specification:
Print $2n$ integers β the rows the passengers will take. The order of passengers should be the same as in input.
Demo Input:
['2\n3 1\n0011\n', '6\n10 8 9 11 13 5\n010010011101\n']
Demo Output:
['2 1 1 2 \n', '6 6 2 3 3 1 4 4 1 2 5 5 \n']
Note:
In the first example the first passenger (introvert) chooses the row $2$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $1$, because it is the only empty row now. The third passenger (extrovert) chooses the row $1$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $2$, because it is the only row with an empty place. | 1,484 |
Title: Pastoral Oddities
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the land of Bovinia there are *n* pastures, but no paths connecting the pastures. Of course, this is a terrible situation, so Kevin Sun is planning to rectify it by constructing *m* undirected paths connecting pairs of distinct pastures. To make transportation more efficient, he also plans to pave some of these new paths.
Kevin is very particular about certain aspects of path-paving. Since he loves odd numbers, he wants each pasture to have an odd number of paved paths connected to it. Thus we call a paving sunny if each pasture is incident to an odd number of paved paths. He also enjoys short paths more than long paths, so he would like the longest paved path to be as short as possible. After adding each path, Kevin wants to know if a sunny paving exists for the paths of Bovinia, and if at least one does, the minimum possible length of the longest path in such a paving. Note that "longest path" here means maximum-weight edge.
Input Specification:
The first line contains two integers *n* (2<=β€<=*n*<=β€<=100<=000) and *m* (1<=β€<=*m*<=β€<=300<=000), denoting the number of pastures and paths, respectively. The next *m* lines each contain three integers *a**i*, *b**i* and *l**i*, describing the *i*-th path. The *i*-th path connects pastures *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*; *a**i*<=β <=*b**i*) and has length *l**i* (1<=β€<=*l**i*<=β€<=109). Paths are given in the order in which they are constructed.
Output Specification:
Output *m* lines. The *i*-th line should contain a single integer denoting the minimum possible length of the longest path (maximum-weight edge) in a sunny paving using only the first *i* paths. If Kevin cannot pave a set of paths so that each pasture is incident to an odd number of paved paths, output <=-<=1.
Note that the paving is only hypotheticalβyour answer after adding the *i*-th path should not be affected by any of your previous answers.
Demo Input:
['4 4\n1 3 4\n2 4 8\n1 2 2\n3 4 3\n', '3 2\n1 2 3\n2 3 4\n', '4 10\n2 1 987\n3 2 829\n4 1 768\n4 2 608\n3 4 593\n3 2 488\n4 2 334\n2 1 204\n1 3 114\n1 4 39\n']
Demo Output:
['-1\n8\n8\n3\n', '-1\n-1\n', '-1\n-1\n829\n829\n768\n768\n768\n488\n334\n204\n']
Note:
For the first sample, these are the paths that Kevin should pave after building the *i*-th path:
1. No set of paths works. 1. Paths 1 (length 4) and 2 (length 8). 1. Paths 1 (length 4) and 2 (length 8). 1. Paths 3 (length 2) and 4 (length 3).
In the second sample, there never exists a paving that makes Kevin happy. | 1,485 |
Title: Numbers
Time Limit: 3 seconds
Memory Limit: 256 megabytes
Problem Description:
One quite ordinary day Valera went to school (there's nowhere else he should go on a week day). In a maths lesson his favorite teacher Ms. Evans told students about divisors. Despite the fact that Valera loved math, he didn't find this particular topic interesting. Even more, it seemed so boring that he fell asleep in the middle of a lesson. And only a loud ringing of a school bell could interrupt his sweet dream.
Of course, the valuable material and the teacher's explanations were lost. However, Valera will one way or another have to do the homework. As he does not know the new material absolutely, he cannot do the job himself. That's why he asked you to help. You're his best friend after all, you just cannot refuse to help.
Valera's home task has only one problem, which, though formulated in a very simple way, has not a trivial solution. Its statement looks as follows: if we consider all positive integers in the interval [*a*;*b*] then it is required to count the amount of such numbers in this interval that their smallest divisor will be a certain integer *k* (you do not have to consider divisor equal to one). In other words, you should count the amount of such numbers from the interval [*a*;*b*], that are not divisible by any number between 2 and *k*<=-<=1 and yet are divisible by *k*.
Input Specification:
The first and only line contains three positive integers *a*, *b*, *k* (1<=β€<=*a*<=β€<=*b*<=β€<=2Β·109,<=2<=β€<=*k*<=β€<=2Β·109).
Output Specification:
Print on a single line the answer to the given problem.
Demo Input:
['1 10 2\n', '12 23 3\n', '6 19 5\n']
Demo Output:
['5\n', '2\n', '0\n']
Note:
Comments to the samples from the statement:
In the first sample the answer is numbers 2,β4,β6,β8,β10.
In the second one β 15,β21
In the third one there are no such numbers. | 1,486 |
Title: Broken Clock
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.
You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.
For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.
Input Specification:
The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively.
The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.
Output Specification:
The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.
Demo Input:
['24\n17:30\n', '12\n17:30\n', '24\n99:99\n']
Demo Output:
['17:30\n', '07:30\n', '09:09\n']
Note:
none | 1,487 |
Title: Cupboard and Balloons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius *r* (the cupboard's top) and two walls of height *h* (the cupboard's sides). The cupboard's depth is *r*, that is, it looks like a rectangle with base *r* and height *h*<=+<=*r* from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right).
Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius . Help Xenia calculate the maximum number of balloons she can put in her cupboard.
You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin.
Input Specification:
The single line contains two integers *r*,<=*h* (1<=β€<=*r*,<=*h*<=β€<=107).
Output Specification:
Print a single integer β the maximum number of balloons Xenia can put in the cupboard.
Demo Input:
['1 1\n', '1 2\n', '2 1\n']
Demo Output:
['3\n', '5\n', '2\n']
Note:
none | 1,488 |
Title: Stepan and Vowels
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".
Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".
There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".
Sergey is very busy and asks you to help him and write the required program.
Input Specification:
The first line contains the integer *n* (1<=β€<=*n*<=β€<=100<=000) β the number of letters in the word written by Stepan.
The second line contains the string *s* which has length that equals to *n* and contains only lowercase English letters β the word written by Stepan.
Output Specification:
Print the single string β the word written by Stepan converted according to the rules described in the statement.
Demo Input:
['13\npobeeeedaaaaa\n', '22\niiiimpleeemeentatiioon\n', '18\naeiouyaaeeiioouuyy\n', '24\naaaoooiiiuuuyyyeeeggghhh\n']
Demo Output:
['pobeda\n', 'implemeentatioon\n', 'aeiouyaeeioouy\n', 'aoiuyeggghhh\n']
Note:
none | 1,489 |
Title: Help Far Away Kingdom
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this:
- If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the numberβs integer part. - If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the numberβs integer part.- If the numberβs integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position.
Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the Kingβs order?
Input Specification:
The first line contains a single number to round up β the integer part (a non-empty set of decimal digits that do not start with 0 β with the exception of a case when the set consists of a single digit β in this case 0 can go first), then follows character Β«.Β» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.
Output Specification:
If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).
Demo Input:
['0.0\n', '1.49\n', '1.50\n', '2.71828182845904523536\n', '3.14159265358979323846\n', '12345678901234567890.1\n', '123456789123456789.999\n']
Demo Output:
['0', '1', '2', '3', '3', '12345678901234567890', 'GOTO Vasilisa.']
Note:
none | 1,490 |
Title: Martian Clock
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" β you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored adventure stories that featured lasers and robots.
Today Petya is watching a shocking blockbuster about the Martians called "R2:D2". What can "R2:D2" possibly mean? It might be the Martian time represented in the Martian numeral system. Petya knows that time on Mars is counted just like on the Earth (that is, there are 24 hours and each hour has 60 minutes). The time is written as "*a*:*b*", where the string *a* stands for the number of hours (from 0 to 23 inclusive), and string *b* stands for the number of minutes (from 0 to 59 inclusive). The only thing Petya doesn't know is in what numeral system the Martian time is written.
Your task is to print the radixes of all numeral system which can contain the time "*a*:*b*".
Input Specification:
The first line contains a single string as "*a*:*b*" (without the quotes). There *a* is a non-empty string, consisting of numbers and uppercase Latin letters. String *a* shows the number of hours. String *b* is a non-empty string that consists of numbers and uppercase Latin letters. String *b* shows the number of minutes. The lengths of strings *a* and *b* are from 1 to 5 characters, inclusive. Please note that strings *a* and *b* can have leading zeroes that do not influence the result in any way (for example, string "008:1" in decimal notation denotes correctly written time).
We consider characters 0, 1, ..., 9 as denoting the corresponding digits of the number's representation in some numeral system, and characters A, B, ..., Z correspond to numbers 10, 11, ..., 35.
Output Specification:
Print the radixes of the numeral systems that can represent the time "*a*:*b*" in the increasing order. Separate the numbers with spaces or line breaks. If there is no numeral system that can represent time "*a*:*b*", print the single integer 0. If there are infinitely many numeral systems that can represent the time "*a*:*b*", print the single integer -1.
Note that on Mars any positional numeral systems with positive radix strictly larger than one are possible.
Demo Input:
['11:20\n', '2A:13\n', '000B:00001\n']
Demo Output:
['3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22', '0\n', '-1\n']
Note:
Let's consider the first sample. String "11:20" can be perceived, for example, as time 4:6, represented in the ternary numeral system or as time 17:32 in hexadecimal system.
Let's consider the second sample test. String "2A:13" can't be perceived as correct time in any notation. For example, let's take the base-11 numeral notation. There the given string represents time 32:14 that isn't a correct time.
Let's consider the third sample. String "000B:00001" can be perceived as a correct time in the infinite number of numeral systems. If you need an example, you can take any numeral system with radix no less than 12. | 1,491 |
Title: Gennady the Dentist
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gennady is one of the best child dentists in Berland. Today *n* children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to *n* in the order they go in the line. Every child is associated with the value of his cofidence *p**i*. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.
While Gennady treats the teeth of the *i*-th child, the child is crying with the volume of *v**i*. At that the confidence of the first child in the line is reduced by the amount of *v**i*, the second one β by value *v**i*<=-<=1, and so on. The children in the queue after the *v**i*-th child almost do not hear the crying, so their confidence remains unchanged.
If at any point in time the confidence of the *j*-th child is less than zero, he begins to cry with the volume of *d**j* and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the *j*-th one in the line is reduced by the amount of *d**j*.
All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.
Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.
Input Specification:
The first line of the input contains a positive integer *n* (1<=β€<=*n*<=β€<=4000) β the number of kids in the line.
Next *n* lines contain three integers each *v**i*,<=*d**i*,<=*p**i* (1<=β€<=*v**i*,<=*d**i*,<=*p**i*<=β€<=106) β the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the *i*-th child.
Output Specification:
In the first line print number *k* β the number of children whose teeth Gennady will cure.
In the second line print *k* integers β the numbers of the children who will make it to the end of the line in the increasing order.
Demo Input:
['5\n4 2 2\n4 1 2\n5 2 4\n3 3 5\n5 1 2\n', '5\n4 5 1\n5 3 9\n4 1 2\n2 1 8\n4 1 9\n']
Demo Output:
['2\n1 3 ', '4\n1 2 4 5 ']
Note:
In the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to β-β2,β1,β3,β1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0,β2,β0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.
In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5,ββ-β1,β6,β8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5,β5,β7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0,β3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last. | 1,492 |
Title: Eleventh Birthday
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
It is Borya's eleventh birthday, and he has got a great present: *n* cards with numbers. The *i*-th card has the number *a**i* written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112.
He is only 11, but he already knows that there are *n*! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112<==<=1192<=Γ<=11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.
Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.
Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.
Input Specification:
Input data contains multiple test cases. The first line of the input data contains an integer *t*Β β the number of test cases (1<=β€<=*t*<=β€<=100). The descriptions of test cases follow.
Each test is described by two lines.
The first line contains an integer *n* (1<=β€<=*n*<=β€<=2000)Β β the number of cards in Borya's present.
The second line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=109)Β β numbers written on the cards.
It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000.
Output Specification:
For each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353.
Demo Input:
['4\n2\n1 1\n3\n1 31 12\n3\n12345 67 84\n9\n1 2 3 4 5 6 7 8 9\n']
Demo Output:
['2\n2\n2\n31680\n']
Note:
none | 1,493 |
Title: Dima and Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dima and Anya love playing different games. Now Dima has imagined a new game that he wants to play with Anya.
Dima writes *n* pairs of integers on a piece of paper (*l**i*,<=*r**i*) (1<=β€<=*l**i*<=<<=*r**i*<=β€<=*p*). Then players take turns. On his turn the player can do the following actions:
1. choose the number of the pair *i* (1<=β€<=*i*<=β€<=*n*), such that *r**i*<=-<=*l**i*<=><=2; 1. replace pair number *i* by pair or by pair . Notation β*x*β means rounding down to the closest integer.
The player who can't make a move loses.
Of course, Dima wants Anya, who will move first, to win. That's why Dima should write out such *n* pairs of integers (*l**i*,<=*r**i*) (1<=β€<=*l**i*<=<<=*r**i*<=β€<=*p*), that if both players play optimally well, the first one wins. Count the number of ways in which Dima can do it. Print the remainder after dividing the answer by number 1000000007Β (109<=+<=7).
Two ways are considered distinct, if the ordered sequences of the written pairs are distinct.
Input Specification:
The first line contains two integers *n*, *p* (1<=β€<=*n*<=β€<=1000,<=1<=β€<=*p*<=β€<=109). The numbers are separated by a single space.
Output Specification:
In a single line print the remainder after dividing the answer to the problem by number 1000000007Β (109<=+<=7).
Demo Input:
['2 2\n', '4 4\n', '100 1000\n']
Demo Output:
['0\n', '520\n', '269568947\n']
Note:
none | 1,494 |
Title: Far Relativeβs Birthday Cake
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a *n*<=Γ<=*n* square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?
Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.
Input Specification:
In the first line of the input, you are given a single integer *n* (1<=β€<=*n*<=β€<=100)Β β the length of the side of the cake.
Then follow *n* lines, each containing *n* characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.
Output Specification:
Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.
Demo Input:
['3\n.CC\nC..\nC.C\n', '4\nCC..\nC..C\n.CC.\n.CC.\n']
Demo Output:
['4\n', '9\n']
Note:
If we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:
1. (1,β2) and (1,β3) 1. (3,β1) and (3,β3) 1. (2,β1) and (3,β1) 1. (1,β3) and (3,β3) | 1,495 |
Title: Room Leader
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.
In the beginning of the round the contestants are divided into rooms. Each room contains exactly *n* participants. During the contest the participants are suggested to solve five problems, *A*, *B*, *C*, *D* and *E*. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.
You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
Input Specification:
The first line contains an integer *n*, which is the number of contestants in the room (1<=β€<=*n*<=β€<=50). The next *n* lines contain the participants of a given room. The *i*-th line has the format of "*handle**i* *plus**i* *minus**i* *a**i* *b**i* *c**i* *d**i* *e**i*" β it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems *A*, *B*, *C*, *D*, *E* correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers:
- 0<=β€<=*plus**i*,<=*minus**i*<=β€<=50; - 150<=β€<=*a**i*<=β€<=500 or *a**i*<==<=0, if problem *A* is not solved; - 300<=β€<=*b**i*<=β€<=1000 or *b**i*<==<=0, if problem *B* is not solved; - 450<=β€<=*c**i*<=β€<=1500 or *c**i*<==<=0, if problem *C* is not solved; - 600<=β€<=*d**i*<=β€<=2000 or *d**i*<==<=0, if problem *D* is not solved; - 750<=β€<=*e**i*<=β€<=2500 or *e**i*<==<=0, if problem *E* is not solved.
All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
Output Specification:
Print on the single line the handle of the room leader.
Demo Input:
['5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0\n']
Demo Output:
['tourist']
Note:
The number of points that each participant from the example earns, are as follows:
- Petr β 3860 - tourist β 4140 - Egor β 4030 - c00lH4x0R β β-β350 - some_participant β 2220
Thus, the leader of the room is tourist. | 1,496 |
Title: Young Photographer
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals *n*. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position *a*1 to position *b*1, the second β from *a*2 to *b*2
What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
Input Specification:
The first line of the input file contains integers *n* and *x*0 (1<=β€<=*n*<=β€<=100; 0<=β€<=*x*0<=β€<=1000). The following *n* lines contain pairs of integers *a**i*,<=*b**i* (0<=β€<=*a**i*,<=*b**i*<=β€<=1000; *a**i*<=β <=*b**i*).
Output Specification:
Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.
Demo Input:
['3 3\n0 7\n14 2\n4 6\n']
Demo Output:
['1\n']
Note:
none | 1,497 |
Title: Help Chef Gerasim
Time Limit: 0 seconds
Memory Limit: 256 megabytes
Problem Description:
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.
To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
Input Specification:
The first line contains integer *n* β the number of cups on the royal table (1<=β€<=*n*<=β€<=1000). Next *n* lines contain volumes of juice in each cup β non-negative integers, not exceeding 104.
Output Specification:
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "*v* ml. from cup #*a* to cup #*b*." (without the quotes), where *v* represents the volume of poured juice, *a* represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), *b* represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
Demo Input:
['5\n270\n250\n250\n230\n250\n', '5\n250\n250\n250\n250\n250\n', '5\n270\n250\n249\n230\n250\n']
Demo Output:
['20 ml. from cup #4 to cup #1.\n', 'Exemplary pages.\n', 'Unrecoverable configuration.\n']
Note:
none | 1,498 |
Title: Mahmoud and Ehab and the bipartiteness
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *u* and *v* belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of *n* nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input Specification:
The first line of input contains an integer *n*Β β the number of nodes in the tree (1<=β€<=*n*<=β€<=105).
The next *n*<=-<=1 lines contain integers *u* and *v* (1<=β€<=*u*,<=*v*<=β€<=*n*, *u*<=β <=*v*)Β β the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output Specification:
Output one integerΒ β the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Demo Input:
['3\n1 2\n1 3\n', '5\n1 2\n2 3\n3 4\n4 5\n']
Demo Output:
['0\n', '2\n']
Note:
Tree definition: [https://en.wikipedia.org/wiki/Tree_(graph_theory)](https://en.wikipedia.org/wiki/Tree_(graph_theory))
Bipartite graph definition: [https://en.wikipedia.org/wiki/Bipartite_graph](https://en.wikipedia.org/wiki/Bipartite_graph)
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2,β3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1,β4) and (2,β5). | 1,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.